-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathPalindromeLinkedList.java
More file actions
38 lines (37 loc) · 1006 Bytes
/
PalindromeLinkedList.java
File metadata and controls
38 lines (37 loc) · 1006 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
33
34
35
36
37
38
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if (head == null) return true;
ListNode quick = head;
ListNode slow = head;
ListNode slowPrev = head;
while (quick != null && quick.next != null) {
quick = quick.next.next;
slowPrev = slow;
slow = slow.next;
}
slowPrev.next = null;
ListNode dummy = new ListNode(0);
while (slow != null) {
ListNode temp = slow.next;
slow.next = dummy.next;
dummy.next = slow;
slow = temp;
}
ListNode n1 = head;
ListNode n2 = dummy.next;
while (n1 != null) {
if (n1.val != n2.val) return false;
n1 = n1.next;
n2 = n2.next;
}
return true;
}
}