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

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

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

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

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

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

return true;
}

public ListNode reverseList(ListNode head) {
ListNode pre = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}

return pre;
}
}

References

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