Add palindrome singly linkedlist optimised approach (#5617)

This commit is contained in:
Nandini Pandey
2024-10-08 00:28:17 +05:30
committed by GitHub
parent 4a5bf39f8e
commit 6868bf8ba0
2 changed files with 115 additions and 0 deletions

View File

@ -30,4 +30,47 @@ public final class PalindromeSinglyLinkedList {
return true;
}
// Optimised approach with O(n) time complexity and O(1) space complexity
public static boolean isPalindromeOptimised(Node head) {
if (head == null || head.next == null) {
return true;
}
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node midNode = slow;
Node prevNode = null;
Node currNode = midNode;
Node nextNode;
while (currNode != null) {
nextNode = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
Node left = head;
Node right = prevNode;
while (left != null && right != null) {
if (left.val != right.val) {
return false;
}
right = right.next;
left = left.next;
}
return true;
}
static class Node {
int val;
Node next;
Node(int val) {
this.val = val;
this.next = null;
}
}
}