-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode234.java
More file actions
48 lines (40 loc) · 1.33 KB
/
LeetCode234.java
File metadata and controls
48 lines (40 loc) · 1.33 KB
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
import java.util.Deque;
import java.util.LinkedList;
import util.ListNode;
public class LeetCode234 {
public static void main(String[] args) {
// 输入:head = [1,2,2,1]
// 输出:true
System.out.println(new Solution234().isPalindrome(ListNode.buildLinkedList(new Integer[] { 1, 2, 2, 1 })));
// 输入:head = [1,2]
// 输出:false
System.out.println(new Solution234().isPalindrome(ListNode.buildLinkedList(new Integer[] { 1, 2 })));
// 输入:head = [1,2,3,2,1]
// 输出:true
System.out.println(new Solution234().isPalindrome(ListNode.buildLinkedList(new Integer[] { 1, 2, 3, 2, 1 })));
}
}
class Solution234 {
public boolean isPalindrome(ListNode head) {
Deque<Integer> stack = new LinkedList<>();
ListNode slow = head;
ListNode fast = head;
stack.push(slow.val);
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
stack.push(slow.val);
}
if (fast.next == null) {
stack.pop();
}
ListNode tail = slow.next;
while (tail != null) {
if (stack.pop() != tail.val) {
return false;
}
tail = tail.next;
}
return true;
}
}