Palindrome Linked List Visualizer & Step-by-Step Algorithm Solution

Determine if a singly linked list is a palindrome in O(n) time and O(1) space using fast/slow pointers and in-place reversal.

Category: linked-list | Difficulty: Easy

Tags: Linked List, Two Pointers, Fast & Slow Pointers, In-Place

Palindrome Linked List

head
1
2
2
1
100%
state
headNode(1)
Initialization
1/34
Explanation

Starting isPalindrome with 4 nodes: [1 -> 2 -> 2 -> 1].

Source Code
1function isPalindrome(head: ListNode | null): boolean {
2 if (!head || !head.next) return true;
3 let slow = head;
4 let fast = head;
5
6 while (fast.next && fast.next.next) {
7 slow = slow.next!;
8 fast = fast.next.next;
9 }
10
11 let right = slow.next;
12 slow.next = null;
13 let prev = null;
14
15 while (right) {
16 const next = right.next;
17 right.next = prev;
18 prev = right;
19 right = next;
20 }
21
22 right = prev;
23 let left = head;
24
25 while (right) {
26 if (left.val !== right.val) return false;
27 left = left.next!;
28 right = right.next;
29 }
30
31 return true;
32}