首页 > 其他分享 >leetcode-234-easy

leetcode-234-easy

时间:2023-01-09 22:12:17浏览次数:47  
标签:deque head false 链表 easy 234 return true leetcode

Palindrome Linked List

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

Example 1:

Input: head = [1,2,2,1]
Output: true
Example 2:

Input: head = [1,2]
Output: false
Constraints:

The number of nodes in the list is in the range [1, 105].
0 <= Node.val <= 9
Follow up: Could you do it in O(n) time and O(1) space?

思路一:刚开始想用栈来实现,后面想想直接用双端队列,先把链表转换成双端队列,然后取队列两头进行对比

    public static boolean isPalindrome(ListNode head) {
        Deque<Integer> deque = new ArrayDeque<>();

        while (head != null) {
            deque.push(head.val);

            head = head.next;
        }

        while (deque.size() > 1) {
            if (!deque.pollFirst().equals(deque.pollLast())) {
                return false;
            }
        }

        return true;
    }

思路二:看了一下题解,有更好的算法,用快慢指针,反转链表的后半部分,最后直接从中间开始比较链表的值

标签:deque,head,false,链表,easy,234,return,true,leetcode
From: https://www.cnblogs.com/iyiluo/p/17038671.html

相关文章

  • leetcode-171-easy
    ExcelSheetColumnNumberGivenastringcolumnTitlethatrepresentsthecolumntitleasappearsinanExcelsheet,returnitscorrespondingcolumnnumber.Fo......
  • leetcode-225-easy
    ImplementStackusingQueuesImplementalast-in-first-out(LIFO)stackusingonlytwoqueues.Theimplementedstackshouldsupportallthefunctionsofanorm......
  • leetcode简单:[1, 9, 13, 14, 20, 21, 26, 27, 35, 58]
    目录1.两数之和9.回文数13.罗马数字转整数14.最长公共前缀20.有效的括号21.合并两个有序链表26.删除有序数组中的重复项27.移除元素35.搜索插入位置58.最后一个......
  • leetcode简单:[66, 67, 70, 83, 121, 141, 160, 169, ,206, 338]
    目录66.加一67.二进制求和70.爬楼梯83.删除排序链表中的重复元素121.买卖股票的最佳时机141.环形链表160.相交链表169.多数元素206.反转链表338.比特位计数66.......
  • LeetCode.977 有序数组的平方
    1.题目给你一个按 非递减顺序 排序的整数数组 ​​​​nums​​​​,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。2.代码classSolution{public......
  • LeetCode 46_ 全排列
    LeetCode46:全排列题目给定一个不含重复数字的数组nums,返回其所有可能的全排列。你可以按任意顺序返回答案。示例1:输入:nums=[1,2,3]输出:[[1,2,3],[1,3,2],......
  • Qt设计可以控制的布局与控件,coordinate &size 12345
    #include"mainwindow.h"#include"ui_mainwindow.h"#include<iostream>#include<QDebug>#include<QBoxLayout>#include<QGridLayout>#include<QFormLayout>#......
  • 242. Valid Anagram [Easy]
    242.ValidAnagramGiventwostringssandt,returntrueiftisananagramofs,andfalseotherwise.AnAnagramisawordorphraseformedbyrearrangingth......
  • [oeasy]python0041_ 转义字符_转义序列_escape_序列_sequence
    转义序列回忆上次内容上次回顾了5bit-Baudot博多码的来历从莫尔斯码到博多码原来人来收发电报现在机器来收发电报输入方式从电键改成键盘......
  • 217. Contains Duplicate [Easy]
    217.ContainsDuplicateGivenanintegerarraynums,returntrueifanyvalueappearsatleasttwiceinthearray,andreturnfalseifeveryelementisdistinc......