-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathPalindromeList.java
87 lines (66 loc) · 2.01 KB
/
PalindromeList.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
75
76
77
78
79
80
81
82
83
84
85
86
87
public class PalindromeList{
public static void main(String[] args){
MyNode root = MyNode.getSampleList();
System.out.println("Original List");
MyNode.display(root);
System.out.println("Is the list palindrome ? "+isPalindrome(root));
}
private static boolean isPalindrome(MyNode root){
MyNode fastPointer = root;
MyNode slowPointer = root;
while(fastPointer!=null){
fastPointer = fastPointer.next;
if(fastPointer!=null){
fastPointer= fastPointer.next;
}
slowPointer = slowPointer.next;
}
MyNode starting = root;
MyNode comparingNode = reverseList(slowPointer);
while(comparingNode!=null){
if(comparingNode.data != starting.data){
return false;
}
comparingNode = comparingNode.next;
starting = starting.next;
}
return true;
}
private static MyNode reverseList(MyNode root){
MyNode current = root;
MyNode next = null;
MyNode prev = null;
while(current!=null){
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}
class MyNode{
public int data ;
public MyNode next ;
MyNode(int data){
this.data = data;
}
protected static MyNode getSampleList(){
MyNode root = new MyNode(1);
root.next = new MyNode(2);
root.next.next = new MyNode(3);
root.next.next.next = new MyNode(3);
root.next.next.next.next = new MyNode(2);
root.next.next.next.next.next = new MyNode(1);
//root.next.next.next.next.next.next = new MyNode(3);
return root;
}
protected static void display(MyNode root){
MyNode temp = root;
while(temp!=null){
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
}