-
Notifications
You must be signed in to change notification settings - Fork 0
/
Palindrome Linked List .java
47 lines (44 loc) · 1.18 KB
/
Palindrome Linked List .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
40
41
42
43
44
45
46
47
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) return true;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
// slow is the middle node
// split the linkedlist to two parts
ListNode tmp = slow.next;
slow.next = null;
// reverse the other half
ListNode newList = reverse(tmp);
ListNode node = head;
while(newList != null){
if(node.val != newList.val){
return false;
}
node = node.next;
newList = newList.next;
}
return true;
}
private ListNode reverse(ListNode node){
ListNode prev = null;
while(node != null){
ListNode tmp = node.next;
node.next = prev;
prev = node;
node = tmp;
}
return prev;
}
}