-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSolution234.java
39 lines (31 loc) · 887 Bytes
/
Solution234.java
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
package leetcode.linkedlist;
import leetcode.ListNode;
public class Solution234 {
public boolean isPalindrome(ListNode head) {
// 快慢指针分开
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode halfHead = reverse(slow);
while (halfHead != null && head != null) {
if (halfHead.val != head.val) {
return false;
}
halfHead = halfHead.next;
head = head.next;
}
return true;
}
private ListNode reverse(ListNode node) {
ListNode pre = null;
while (node != null) {
ListNode temp = node.next;
node.next = pre;
pre = node;
node = temp;
}
return pre;
}
}