File tree 1 file changed +42
-0
lines changed
src/main/java/com/thealgorithms/misc
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -30,4 +30,46 @@ public static boolean isPalindrome(final SinglyLinkedList linkedList) {
30
30
31
31
return true ;
32
32
}
33
+
34
+ public static boolean isPalindromeOptimised (Node head ){
35
+ if (head ==null || head .next ==null ){
36
+ return true ;
37
+ }
38
+ Node slow = head ;
39
+ Node fast =head ;
40
+ while (fast !=null && fast .next !=null ){
41
+ slow =slow .next ;
42
+ fast =fast .next .next ;
43
+ }
44
+ Node midNode = slow ;
45
+
46
+ Node prevNode =null ;
47
+ Node currNode =midNode ;
48
+ Node nextNode ;
49
+ while (currNode !=null ){
50
+ nextNode =currNode .next ;
51
+ currNode .next =prevNode ;
52
+ prevNode =currNode ;
53
+ currNode =nextNode ;
54
+ }
55
+ Node left =head ;
56
+ Node right =prevNode ;
57
+ while (left !=null && right !=null ){
58
+ if (left .val !=right .val ){
59
+ return false ;
60
+ }
61
+ right =right .next ;
62
+ left =left .next ;
63
+ }
64
+ return true ;
65
+
66
+ }
67
+ static class Node {
68
+ int val ;
69
+ Node next ;
70
+ public Node (int val ) {
71
+ this .val = val ;
72
+ this .next = null ;
73
+ }
74
+ }
33
75
}
You can’t perform that action at this time.
0 commit comments