Skip to content

Commit a490f2d

Browse files
Optimized approach for palindrome linked list
1 parent be8df21 commit a490f2d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,46 @@ public static boolean isPalindrome(final SinglyLinkedList linkedList) {
3030

3131
return true;
3232
}
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+
}
3375
}

0 commit comments

Comments
 (0)