forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome.java
79 lines (68 loc) · 2.13 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
package com.rampatra.linkedlists;
import com.rampatra.base.LinkedStack;
import com.rampatra.base.SingleLinkedList;
import com.rampatra.base.SingleLinkedNode;
import com.rampatra.base.Stack;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 6/18/15
*/
public class Palindrome<E extends Comparable<E>> extends SingleLinkedList<E> {
/**
* Uses Stack to test whether a linked list starting
* from {@param node} is palindrome or not.
*
* @param list
* @return {@code true} if linked list palindrome, {@code false} otherwise.
*/
private static <E extends Comparable<E>> boolean isPalindrome(SingleLinkedList<E> list) {
SingleLinkedNode<E> head = list.getNode(0);
SingleLinkedNode<E> curr = head;
Stack<SingleLinkedNode<E>> stack = new LinkedStack<>();
while (curr != null) {
stack.push(curr);
curr = curr.next;
}
curr = head;
while (curr != null) {
if (curr.item != stack.pop().item) {
return false;
}
curr = curr.next;
}
return true;
}
/**
* Recursive function to test whether a linked list
* starting from {@param node} is palindrome or not.
* <p/>
* NOTE: This method moves the head reference. (disadvantage)
*
* @param node
* @return
*/
private boolean isPalindromeRecursive(SingleLinkedNode<E> node) {
if (node == null) return true;
boolean isPalindrome = isPalindromeRecursive(node.next);
if (head.item == node.item) {
head = head.next;
return isPalindrome;
} else {
return false;
}
}
public static void main(String[] args) {
Palindrome<Integer> linkedList = new Palindrome<>();
linkedList.add(0);
linkedList.add(1);
linkedList.add(2);
linkedList.add(1);
linkedList.add(0);
linkedList.printList();
System.out.println(isPalindrome(linkedList));
linkedList.printList();
System.out.println(linkedList.isPalindromeRecursive(linkedList.getNode(0)));
}
}