Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

0%

Leetcode 234 回文联表(Palindrome Linked List) 题解分析

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false
Example 2:

Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
ListNode tail = head;
LinkedList<Integer> stack = new LinkedList<>();
// 循环入栈
while (tail != null) {
stack.push(tail.val);
tail = tail.next;
}
// 再遍历链表跟出栈的对比,其实就是正反序的对比
while (!stack.isEmpty()) {
if (stack.peekFirst() == head.val) {
stack.pollFirst();
head = head.next;
} else {
return false;
}
}
return true;

// return stack.isEmpty();
}
}
请我喝杯咖啡