-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeLL.java
More file actions
39 lines (33 loc) · 1.01 KB
/
PalindromeLL.java
File metadata and controls
39 lines (33 loc) · 1.01 KB
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
class PalindromeLL {
public ListNode reverse(ListNode head) {
if (head == null) return null;
ListNode prev = null;
ListNode curr = head;
ListNode nextNode = null;
while (curr != null) {
nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode reverseHead = reverse(slow);
ListNode temp1 = head;
ListNode temp2 = reverseHead;
while (temp2 != null) {
if (temp1.val != temp2.val) return false;
temp1 = temp1.next;
temp2 = temp2.next;
}
return true;
}
}