1
1
package me .ramswaroop .linkedlists ;
2
2
3
+ import me .ramswaroop .common .LinkedStack ;
3
4
import me .ramswaroop .common .SingleLinkedList ;
4
5
import me .ramswaroop .common .SingleLinkedNode ;
6
+ import me .ramswaroop .common .Stack ;
5
7
6
8
/**
7
9
* Created by IntelliJ IDEA.
12
14
*/
13
15
public class IsPalindrome <E > extends SingleLinkedList <E > {
14
16
17
+ /**
18
+ * Uses Stack to test whether a linked list starting
19
+ * from {@param node} is palindrome or not.
20
+ *
21
+ * @param node
22
+ * @return
23
+ */
24
+ public static <E > boolean isPalindrome (SingleLinkedNode <E > node ) {
25
+ SingleLinkedNode <E > curr = node ;
26
+ Stack <SingleLinkedNode <E >> stack = new LinkedStack <>();
27
+
28
+ while (curr != null ) {
29
+ stack .push (curr );
30
+ curr = curr .next ;
31
+ }
32
+
33
+ curr = node ;
34
+
35
+ while (curr != null ) {
36
+ if (curr .item != stack .pop ().item ) {
37
+ return false ;
38
+ }
39
+ curr = curr .next ;
40
+ }
41
+
42
+ return true ;
43
+ }
44
+
15
45
/**
16
46
* Recursive function to test whether a linked list
17
- * is palindrome or not.
47
+ * starting from {@param node} is palindrome or not.
18
48
* <p/>
19
49
* NOTE: This method moves the head reference. (disadvantage)
20
50
*
21
51
* @param node
22
52
* @return
23
53
*/
24
- public boolean isPalindrome (SingleLinkedNode <E > node ) {
54
+ public boolean isPalindromeRecursive (SingleLinkedNode <E > node ) {
25
55
if (node == null ) return true ;
26
56
27
- boolean isPalindrome = isPalindrome (node .next );
57
+ boolean isPalindrome = isPalindromeRecursive (node .next );
28
58
29
59
if (head .item == node .item ) {
30
60
head = head .next ;
@@ -42,6 +72,8 @@ public static void main(String a[]) {
42
72
linkedList .add (11 );
43
73
linkedList .add (00 );
44
74
linkedList .printList ();
45
- System .out .println (linkedList .isPalindrome (linkedList .getNode (0 )));
75
+ System .out .println (isPalindrome (linkedList .getNode (0 )));
76
+ linkedList .printList ();
77
+ System .out .println (linkedList .isPalindromeRecursive (linkedList .getNode (0 )));
46
78
}
47
79
}
0 commit comments