Skip to content

Commit a3b7d0b

Browse files
committed
Fixes #2360 Palindrome Linked List
1 parent 64513ff commit a3b7d0b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Misc/PalindromeSinglyLinkedList.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package Misc;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* A simple way of knowing if a singly linked list is palindrome is to
7+
* push all the values into a Stack and then compare the list to popped
8+
* vales from the Stack.
9+
*
10+
* See more: https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
11+
*/
12+
public class PalindromeSinglyLinkedList {
13+
public static void main(String[] args) {
14+
Node node5 = new Node(3, null);
15+
Node node4 = new Node(2, node5);
16+
Node node3 = new Node(1, node4);
17+
Node node2 = new Node(2, node3);
18+
Node node1 = new Node(3, node2);
19+
// Node node1 = new Node(2, node2);
20+
21+
if (isPalindrome(node1)) {
22+
System.out.println("It's a palindrome list");
23+
} else {
24+
System.out.println("It's NOT a palindrome list");
25+
}
26+
}
27+
28+
public static boolean isPalindrome(Node head) {
29+
boolean ret = true;
30+
Node tempNode = head;
31+
Stack<Integer> linkedListValues = new Stack<>();
32+
33+
while (tempNode != null) {
34+
linkedListValues.push(tempNode.data);
35+
tempNode = tempNode.nextNode;
36+
}
37+
38+
while (head != null) {
39+
if (head.data != linkedListValues.pop()) {
40+
ret = false;
41+
break;
42+
}
43+
44+
head = head.nextNode;
45+
}
46+
47+
return ret;
48+
}
49+
}
50+
51+
class Node {
52+
int data;
53+
Node nextNode;
54+
55+
public Node(int data, Node nextNode) {
56+
this.data = data;
57+
this.nextNode = nextNode;
58+
}
59+
}

0 commit comments

Comments
 (0)