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