-
Notifications
You must be signed in to change notification settings - Fork 0
/
Palindrome LL.java
37 lines (35 loc) · 898 Bytes
/
Palindrome LL.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
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null)
return true;
ListNode middle = findMiddle(head);
ListNode revHead = findReverse(middle);
ListNode cur = head;
while (cur != null && revHead != null) {
if (cur.val != revHead.val) {
return false;
}
cur = cur.next;
revHead = revHead.next;
}
return true;
}
private ListNode findReverse(ListNode middle) {
if (middle == null || middle.next == null) {
return middle;
}
ListNode p = findReverse(middle.next);
middle.next.next = middle;
middle.next = null;
return p;
}
private ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}