- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathPalindromeLinkedList.java
43 lines (38 loc) · 1.2 KB
/
PalindromeLinkedList.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
// https://leetcode.com/problems/palindrome-linked-list/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
classSolution {
publicbooleanisPalindrome(ListNodehead) {
if(head == null || (head != null && head.next == null)) returntrue;
ListNodeslow = head, fast = head.next, prevFast = head;
while(fast != null && fast.next != null){
slow = slow.next;
prevFast = fast.next;
fast = fast.next.next;
}
ListNodeprev = null, curr = slow.next, next = null;
slow.next = (fast == null) ? prevFast : fast;
while(curr != null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
ListNodetemp = head;
curr = slow.next;
while(curr != null){
if(temp.val != curr.val) returnfalse;
temp = temp.next;
curr = curr.next;
}
returntrue;
}
}