Poison

234. Palindrome Linked List

Stack
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
class Solution {
public boolean isPalindrome(ListNode head) {
// d * * * * *
// f f f f
// s s s s

// d * * * * * *
// f f f f
// s s s s

ListNode dummyHead = new ListNode();
dummyHead.next = head;

Stack<Integer> stack = new Stack<>();
ListNode fast = dummyHead, slow = dummyHead;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast != null) {
stack.push(slow.val);
}
}

ListNode curr = slow.next;
while (curr != null && curr.val == stack.peek()) {
stack.pop();
curr = curr.next;
}

return stack.isEmpty();
}
}
Linked List
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
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public boolean isPalindrome(ListNode head) {
if (head.next == null) {
return true;
}

// d -> 1 -> 2 -> 3
// f
// s

// d -> 1 -> 2 -> 3 -> 4
// f
// s

ListNode dummyHead = new ListNode(-1, head);
ListNode fast = dummyHead, slow = dummyHead;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}

ListNode rightHead = slow.next;
slow.next = null;
ListNode reversedRightHead = reverse(rightHead);
ListNode nodeA = head, nodeB = reversedRightHead;
while (nodeB != null) {
if (nodeB.val != nodeA.val) {
return false;
}
nodeB = nodeB.next;
nodeA = nodeA.next;
}

return true;
}

private ListNode reverse(ListNode node) {
ListNode pre = null;
while (node != null) {
ListNode next = node.next;
node.next = pre;
pre = node;
node = next;
}

return pre;
}
}
Reference

234. Palindrome Linked List
剑指 Offer II 027. 回文链表