-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeLinkedList.java
More file actions
52 lines (46 loc) · 1.51 KB
/
PalindromeLinkedList.java
File metadata and controls
52 lines (46 loc) · 1.51 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
package leetcode;
import utils.ListNode;
import utils.Lists;
/**
* PalindromeLinkedList
* https://leetcode-cn.com/problems/palindrome-linked-list/
*
* @since 2020-10-23
*/
public class PalindromeLinkedList {
public static void main(String[] args) {
// ListNode head = Lists.fromInts(new int[]{1, 2, 2, 1}, -1);
// ListNode head = Lists.fromInts(new int[]{1}, -1);
// ListNode head = null;
// ListNode head = Lists.fromInts(new int[]{1, 2}, -1);
ListNode head = Lists.fromInts(new int[]{1, 2, 2}, -1);
PalindromeLinkedList sol = new PalindromeLinkedList();
System.out.println(sol.isPalindrome(head));
}
public boolean isPalindrome(ListNode head) {
ListNode node = recursiveCompare(head, head);
return head == null || node != null;
}
public ListNode recursiveCompare(ListNode head, ListNode negative) {
ListNode positive = null;
if (negative != null) {
// go to the end
positive = recursiveCompare(head, negative.next);
} else {
// stop recursive, return head for compare
return head;
}
if (positive != null) {
if (positive.val == negative.val) {
if (positive.next != null) {
// iteration for next value
return positive.next;
} else {
// finish compare
return head;
}
}
}
return null;
}
}