forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeLinkedList.java
More file actions
32 lines (30 loc) · 878 Bytes
/
PalindromeLinkedList.java
File metadata and controls
32 lines (30 loc) · 878 Bytes
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
public class PalindromeLinkedList {
// 耗时2ms
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
fast = reverse(slow);
/**
* 注意退出条件是p1 != slow
*/
for (ListNode p1 = head, p2 = fast; p1 != slow; p1 = p1.next, p2 = p2.next) {
if (p1.val != p2.val) {
return false;
}
}
return true;
}
private ListNode reverse(ListNode node) {
ListNode dummy = new ListNode(0), cur = dummy;
while (node != null) {
ListNode next = node.next;
node.next = cur.next;
cur.next = node;
node = next;
}
return dummy.next;
}
}