-
-
Notifications
You must be signed in to change notification settings - Fork 316
/
Palindrome.java
107 lines (94 loc) · 3.12 KB
/
Palindrome.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.ctci.linkedlists;
import java.util.Stack;
/**
* @author rampatra
* @since 2019-02-02
*/
public class Palindrome {
/**
* Checks whether a Linked List is palindrome by using a stack.
*
* @param head starting node of the linked list.
* @return {@code true} if linked list palindrome, {@code false} otherwise.
*/
private static boolean isPalindrome(Node head) {
Node curr = head;
Stack<Integer> stack = new Stack<>();
// pop all elements into stack
while (curr != null) {
stack.push(curr.val);
curr = curr.next;
}
curr = head;
// as stack contains the elements in reverse order, pop and compare with the list one by one
while (curr != null) {
if (curr.val != stack.pop()) {
return false;
}
curr = curr.next;
}
return true;
}
/**
* This is a similar approach like above but a bit faster as we are not iterating the entire list twice.
*
* @param head starting node of the linked list.
* @return {@code true} if linked list palindrome, {@code false} otherwise.
*/
private static boolean isPalindromeOptimized(Node head) {
Node slow = head;
Node fast = head;
Stack<Integer> stack = new Stack<>();
// push half of the elements into the stack
while (fast != null && fast.next != null) {
stack.push(slow.val);
slow = slow.next;
fast = fast.next.next;
}
// linked list has odd number of elements, so forward the slow reference by one
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
if (slow.val != stack.pop()) {
return false;
}
slow = slow.next;
}
return true;
}
public static void main(String[] args) {
Node l1 = new Node(1);
l1.next = new Node(2);
l1.next.next = new Node(3);
l1.next.next.next = new Node(3);
l1.next.next.next.next = new Node(2);
l1.next.next.next.next.next = new Node(1);
l1.print();
System.out.println(isPalindrome(l1));
System.out.println(isPalindromeOptimized(l1));
System.out.println("------");
l1 = new Node(1);
l1.next = new Node(2);
l1.next.next = new Node(3);
l1.next.next.next = new Node(2);
l1.next.next.next.next = new Node(1);
l1.print();
System.out.println(isPalindrome(l1));
System.out.println(isPalindromeOptimized(l1));
System.out.println("------");
l1 = new Node(0);
l1.next = new Node(2);
l1.next.next = new Node(3);
l1.next.next.next = new Node(3);
l1.next.next.next.next = new Node(0);
l1.print();
System.out.println(isPalindrome(l1));
System.out.println(isPalindromeOptimized(l1));
System.out.println("------");
l1 = new Node(1);
l1.print();
System.out.println(isPalindrome(l1));
System.out.println(isPalindromeOptimized(l1));
}
}