-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_234.java
More file actions
43 lines (38 loc) · 1.12 KB
/
Copy pathP_234.java
File metadata and controls
43 lines (38 loc) · 1.12 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
package leetcode.easy;
import utils.DataStructures.ListNode;
@SuppressWarnings({ "ConstantConditions", "TailRecursion" })
public class P_234 {
public boolean isPalindrome(ListNode head) {
final ListNode dummy = new ListNode(-1);
dummy.next = head;
final ListNode mid = findMiddle(dummy);
final ListNode t = mid.next;
mid.next = null;
ListNode rev = reverse(t, null);
while (rev != null) {
if (head.val != rev.val) {
return false;
}
rev = rev.next;
head = head.next;
}
return true;
}
private static ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private static ListNode reverse(ListNode node, ListNode tail) {
if (node == null) {
return tail;
}
final ListNode next = node.next;
node.next = tail;
return reverse(next, node);
}
}