forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0234-palindrome-linked-list.java
35 lines (32 loc) · 1018 Bytes
/
0234-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
//reverse the later half
//after reversing just start comparing if at any time the value doesn't match it's not a palindrome, i.e. return false, else it's a palindrome and return true.
//It'll automatically take care of the edge cases of odd and even
classSolution {
publicbooleanisPalindrome(ListNodehead) {
ListNodefast = head;
ListNodeslow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNodetemp = reverse(slow);
while (temp != null && head != null) {
if (temp.val != head.val) returnfalse;
temp = temp.next;
head = head.next;
}
returntrue;
}
publicListNodereverse(ListNodehead) {
ListNodep = null;
ListNodeq = null;
ListNoder = head;
while (r != null) {
p = q;
q = r;
r = r.next;
q.next = p;
}
returnq;
}
}