mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 09:06:51 +08:00
Add palindrome singly linkedlist optimised approach (#5617)
This commit is contained in:
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user