I’m using 2 pointers.
- slow - starts on the head
- fast - starts at the end
We link the fast node to the head node like a circular linked list.
Next,
-
We move p1 by the next forward position
-
We move p2 by the (n-1) forward position where n is the total length of the linked list.
-
We check for p1.val == p2.val
-
We check till we reach the common point (p1==p2)
public static boolean isPalindrome(Node head) { int n = findListLength(head); Node p1 = head, p2 = head; // move p2 by (n-1) positions foreward while(p2.next!=null) p2 = p2.next; // link both the nodes p2.next = p1; while(p1!=p2) { p1 = p1.next; int pos = n-1; while(pos-- > 0) { p2 = p2.next; } if(p1.val != p2.val) return false; } return true; } public static int findListLength(Node node) { int c=0; Node curr = node; while(curr!=null) { curr = curr.next; ++c; } return c; }
I understand that we ended up modifying the actual linked list but just wanted to know if this can be a solution.