Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c84eb46

Browse files
author
Ram swaroop
committed
IsPalindrome done (using stack)
1 parent 452f28c commit c84eb46

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

src/me/ramswaroop/linkedlists/IsPalindrome.java

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package me.ramswaroop.linkedlists;
22

3+
import me.ramswaroop.common.LinkedStack;
34
import me.ramswaroop.common.SingleLinkedList;
45
import me.ramswaroop.common.SingleLinkedNode;
6+
import me.ramswaroop.common.Stack;
57

68
/**
79
* Created by IntelliJ IDEA.
@@ -12,19 +14,47 @@
1214
*/
1315
public class IsPalindrome<E> extends SingleLinkedList<E> {
1416

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+
1545
/**
1646
* Recursive function to test whether a linked list
17-
* is palindrome or not.
47+
* starting from {@param node} is palindrome or not.
1848
* <p/>
1949
* NOTE: This method moves the head reference. (disadvantage)
2050
*
2151
* @param node
2252
* @return
2353
*/
24-
public boolean isPalindrome(SingleLinkedNode<E> node) {
54+
public boolean isPalindromeRecursive(SingleLinkedNode<E> node) {
2555
if (node == null) return true;
2656

27-
boolean isPalindrome = isPalindrome(node.next);
57+
boolean isPalindrome = isPalindromeRecursive(node.next);
2858

2959
if (head.item == node.item) {
3060
head = head.next;
@@ -42,6 +72,8 @@ public static void main(String a[]) {
4272
linkedList.add(11);
4373
linkedList.add(00);
4474
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)));
4678
}
4779
}

0 commit comments

Comments
 (0)