-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMain.java
More file actions
54 lines (53 loc) · 1.6 KB
/
Main.java
File metadata and controls
54 lines (53 loc) · 1.6 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class PalindromeLinkedList234 {
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode fast = head;
ListNode slow = head;
ListNode left = new ListNode(-1), right = new ListNode(-1);
while (fast != null) {
if (fast.next == null) {
left = right = slow;
break;
}
fast = fast.next;
if (fast.next == null) {
left = slow;
right = slow.next;
break;
}
fast = fast.next;
slow = slow.next;
}
if (left.val != right.val) {
return false;
}
left = reverse(head, left);
right = right.next;
while (left != null && right != null) {
if (left.val != right.val) {
return false;
}
left = left.next;
right = right.next;
}
return true;
}
private ListNode reverse (ListNode head, ListNode end) {
if (head == end) {
return null;
}
ListNode prev = head;
head = head.next;
while (head != end) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
}