-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindrommeLinkedList.java
74 lines (63 loc) · 1.42 KB
/
PalindrommeLinkedList.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package ProjectFiles;
public class PalindrommeLinkedList {
public static void main(String[] args) {
ListNode h = new ListNode(1);
h.next = new ListNode(1);
h.next.next = new ListNode(1);
ListNode t = h.next.next;
t.next = new ListNode(2);
t.next.next = new ListNode(1);
t.next.next.next = null;
ListNode root = h;
// while(root != null){
// System.out.println(root.val);
// root= root.next;
// }
System.out.println(isPalindrome(h.next));
}
public static boolean isPalindrome(ListNode head) {
if(head == null){
return false;
}
PalindrommeResult result = new PalindrommeResult(true, false);
isPalindromeRec(head, head,result );
return result.r;
}
private static ListNode isPalindromeRec(ListNode cur, ListNode head, PalindrommeResult r) {
if(r.done)
return null;
if(cur.next == null){
if(head.val != cur.val){
r.r = false;
}
return head.next;
}
else{
ListNode comparableNode = isPalindromeRec(cur.next, head, r);
if(comparableNode == null){
return null;
}
if(cur == comparableNode || comparableNode.next == cur){
r.done = true;
}
if(r.r == false){
return comparableNode.next;
}
if(comparableNode.val != cur.val){
r.r = false;
}
else{
return comparableNode.next;
}
}
return null;
}
}
class PalindrommeResult{
boolean r;
boolean done;
PalindrommeResult(boolean val, boolean d) {
d = done;
r= val;
}
}