File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ package Misc ;
2
+
3
+ import java .util .Stack ;
4
+ import DataStructures .Lists .SinglyLinkedList ;
5
+
6
+ /**
7
+ * A simple way of knowing if a singly linked list is palindrome is to
8
+ * push all the values into a Stack and then compare the list to popped
9
+ * vales from the Stack.
10
+ *
11
+ * See more: https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
12
+ */
13
+ public class PalindromeSinglyLinkedList {
14
+ public static void main (String [] args ) {
15
+ SinglyLinkedList linkedList = new SinglyLinkedList ();
16
+
17
+ linkedList .insertHead (3 );
18
+ linkedList .insertNth (2 , 1 );
19
+ linkedList .insertNth (1 , 2 );
20
+ linkedList .insertNth (2 , 3 );
21
+ linkedList .insertNth (3 , 4 );
22
+
23
+ if (isPalindrome (linkedList )) {
24
+ System .out .println ("It's a palindrome list" );
25
+ } else {
26
+ System .out .println ("It's NOT a palindrome list" );
27
+ }
28
+ }
29
+
30
+ public static boolean isPalindrome (SinglyLinkedList linkedList ) {
31
+ boolean ret = true ;
32
+ Stack <Integer > linkedListValues = new Stack <>();
33
+
34
+ for (int i = 0 ; i < linkedList .size (); i ++) {
35
+ linkedListValues .push (linkedList .getNth (i ));
36
+ }
37
+
38
+ for (int i = 0 ; i < linkedList .size (); i ++) {
39
+ if (linkedList .getNth (i ) != linkedListValues .pop ()) {
40
+ ret = false ;
41
+ break ;
42
+ }
43
+ }
44
+
45
+ return ret ;
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments