-
Notifications
You must be signed in to change notification settings - Fork 2
/
PalindromeLinkedList.java
39 lines (37 loc) · 1.14 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
public class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode firstHalf = head;
ListNode secondHalf = slow.next;
slow.next = null;
ListNode newSecondHalf = reverseList(secondHalf);
while (firstHalf != null && newSecondHalf != null) {
if (firstHalf.val != newSecondHalf.val) {
return false;
}
firstHalf = firstHalf.next;
newSecondHalf = newSecondHalf.next;
}
return true;
}
public ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = head;
while (p != null && p.next != null) {
ListNode temp = p.next;
p.next = temp.next;
temp.next = dummy.next;
dummy.next = temp;
}
return dummy.next;
}
}