Palindrome linked list
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A palindrome reads the same forward and backward, like "madam". With a chain you cannot read backward, so the trick is to find the middle, flip the second half, and compare it with the first half. No copy of the data is needed.
Practical use cases
- Web app: Validating symmetric voucher codes. A marketing team issues "lucky" codes that read the same both ways, and the checker must verify them. Each code is stored as a chain of characters. The checker finds the middle, reverses the second half and compares, so a code is verified in a single short pass.
- Web app: A word-game answer checker. A browser word game asks the player to enter palindromes and checks each entry as they type. The server stores letters in a chain and checks symmetry without building a second reversed copy, which keeps memory use steady when thousands of players play at once.
- System: Sequence analysis tools. Tools that scan long DNA-style sequences look for mirrored stretches that read the same in both directions. Finding the middle, reversing one half and comparing the halves checks each stretch without making a full copy, which matters when the sequences are very large.
The story: Mrs. Sharma's Mirror Words
Mrs. Sharma loved words that read the same both ways: MADAM, LEVEL, RADAR. One day she wrote a word on the board, one letter per paper slip, each slip holding the next slip like a chain. "Is this word a palindrome?" she asked the class.
Aarav shouted, "Read from both ends and compare!" But the slips only knew forward. The last letter could not point back. Kabir tried copying all letters to a notebook (extra memory) and reading it backward. That works, but Mrs. Sharma asked: "Can you do it without a notebook?"
Mira thought: "I only need the second half to face backward. Find the middle, flip the arrows of the second half, then walk from both ends toward the middle comparing letters." She used the slow-and-fast trick for the middle and the reversal trick (from the earlier train-coach lesson) for the flip.
Letter by letter: M with M, A with A, D with D. All matched! For R-A-J-A, R met A and Mira stopped at once: not a palindrome. And being polite, she flipped the second half back so the board looked the same as before. That is the palindrome linked list check in O(n) time and O(1) extra memory.
How to spot this problem, and where you need it
You need to know whether a sequence reads the same from both ends, but the data can only be walked in one direction and you do not want to copy it all.
Signs you need it
- The task says "palindrome", "symmetric" or "mirror" and the data is a one-way chain or a stream.
- Your first idea is to copy everything into an array and compare, and you are asked to use little extra memory.
- You can already find the middle and reverse a list, and the problem feels like a mix of those two.
Where to use it in a project
- Validation of symmetric codes, ids or tokens stored as chains.
- Word and puzzle games and quiz apps that check whether the text a player typed reads the same both ways.
- Sequence-matching tasks in analytics or bio-data tools, where mirrored patterns carry meaning.
The solution
Find the middle with a slow and a fast walker. Reverse the second half of the chain in place. Now walk the first half and the reversed second half together, comparing item by item; if any pair differs, it is not a palindrome. Optionally reverse the second half back afterwards so the data is left unchanged.
Payoff: Before: a full extra copy of the data. After: no extra copy, one pass to the middle, one to reverse and one to compare.
Explain it like I am 8
Put a mirror in the middle of the word. If the left half and the reflection of the right half look exactly the same, the word is a palindrome. We "make the mirror" by turning the second half around.
How it works, step by step
- Find the middle using slow and fast pointers.
- Reverse the second half of the list (from the middle node onward).
- Compare: walk one pointer from the head and another from the reversed half, checking the values are equal. Stop when the reversed half runs out.
- If any pair differs, it is not a palindrome. If all match, it is.
- Optional but polite: reverse the second half again to restore the original list.
The code in four languages
PHP
<?php
class Node {
public $val;
public ?Node $next = null;
public function __construct($val, ?Node $next = null) { $this->val = $val; $this->next = $next; }
}
function fromArray(array $vals): ?Node {
$head = null;
foreach (array_reverse($vals) as $v) { $head = new Node($v, $head); }
return $head;
}
function reverse(?Node $head): ?Node {
$prev = null;
while ($head !== null) {
$nxt = $head->next;
$head->next = $prev; // flip the arrow
$prev = $head;
$head = $nxt;
}
return $prev;
}
function isPalindrome(?Node $head): bool {
if ($head === null || $head->next === null) return true;
$slow = $head; $fast = $head; // 1) find the middle
while ($fast !== null && $fast->next !== null) {
$slow = $slow->next;
$fast = $fast->next->next;
}
$second = reverse($slow); // 2) flip the second half
$copy = $second; // remember it so we can restore later
$ok = true;
for ($p = $head, $q = $second; $q !== null; $p = $p->next, $q = $q->next) { // 3) compare
if ($p->val !== $q->val) { $ok = false; break; }
}
reverse($copy); // 4) restore the list
return $ok;
}
foreach (['MADAM', 'ABBA', 'RAJA', 'X'] as $word) {
$list = fromArray(str_split($word));
echo $word . ': ' . (isPalindrome($list) ? 'palindrome' : 'not a palindrome') . "\n";
}JavaScript
class Node {
constructor(val, next = null) { this.val = val; this.next = next; }
}
function fromArray(vals) {
let head = null;
for (let i = vals.length - 1; i >= 0; i--) head = new Node(vals[i], head);
return head;
}
function reverse(head) {
let prev = null;
while (head !== null) {
const nxt = head.next;
head.next = prev; // flip the arrow
prev = head;
head = nxt;
}
return prev;
}
function isPalindrome(head) {
if (head === null || head.next === null) return true;
let slow = head, fast = head; // 1) find the middle
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
}
const second = reverse(slow); // 2) flip the second half
let ok = true;
for (let p = head, q = second; q !== null; p = p.next, q = q.next) { // 3) compare
if (p.val !== q.val) { ok = false; break; }
}
reverse(second); // 4) restore the list
return ok;
}
for (const word of ['MADAM', 'ABBA', 'RAJA', 'X']) {
const list = fromArray(word.split(''));
console.log(word + ': ' + (isPalindrome(list) ? 'palindrome' : 'not a palindrome'));
}Java
public class Main {
static class Node {
char val;
Node next;
Node(char val, Node next) { this.val = val; this.next = next; }
}
static Node fromString(String s) {
Node head = null;
for (int i = s.length() - 1; i >= 0; i--) head = new Node(s.charAt(i), head);
return head;
}
static Node reverse(Node head) {
Node prev = null;
while (head != null) {
Node nxt = head.next;
head.next = prev; // flip the arrow
prev = head;
head = nxt;
}
return prev;
}
static boolean isPalindrome(Node head) {
if (head == null || head.next == null) return true;
Node slow = head, fast = head; // 1) find the middle
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node second = reverse(slow); // 2) flip the second half
Node copy = second; // remember it so we can restore later
boolean ok = true;
for (Node p = head, q = second; q != null; p = p.next, q = q.next) { // 3) compare
if (p.val != q.val) { ok = false; break; }
}
reverse(copy); // 4) restore the list
return ok;
}
public static void main(String[] args) {
for (String word : new String[]{"MADAM", "ABBA", "RAJA", "X"}) {
Node list = fromString(word);
System.out.println(word + ": " + (isPalindrome(list) ? "palindrome" : "not a palindrome"));
}
}
}Go
package main
import "fmt"
type Node struct {
val rune
next *Node
}
func fromString(s string) *Node {
runes := []rune(s)
var head *Node
for i := len(runes) - 1; i >= 0; i-- {
head = &Node{val: runes[i], next: head}
}
return head
}
func reverse(head *Node) *Node {
var prev *Node
for head != nil {
nxt := head.next
head.next = prev // flip the arrow
prev = head
head = nxt
}
return prev
}
func isPalindrome(head *Node) bool {
if head == nil || head.next == nil {
return true
}
slow, fast := head, head // 1) find the middle
for fast != nil && fast.next != nil {
slow = slow.next
fast = fast.next.next
}
second := reverse(slow) // 2) flip the second half
saved := second // remember it so we can restore later
ok := true
for p, q := head, second; q != nil; p, q = p.next, q.next { // 3) compare
if p.val != q.val {
ok = false
break
}
}
reverse(saved) // 4) restore the list
return ok
}
func main() {
for _, word := range []string{"MADAM", "ABBA", "RAJA", "X"} {
verdict := "not a palindrome"
if isPalindrome(fromString(word)) {
verdict = "palindrome"
}
fmt.Println(word + ": " + verdict)
}
}Time: O(n) · Extra space: O(1). Three passes (middle, reverse, compare), each linear, using only a few pointers. Copying into an array would be O(n) space.
Watch out for
- Comparing the first half with the second half without reversing it, which compares in the wrong order.
- Leaving the list damaged. After reversing half of it, the original is changed unless you reverse it back.
- Mishandling odd lengths: the middle node is compared with itself, which is fine. Do not skip or double count it.
Quick check
- Why do we reverse the second half?
- To sort it
- So we can read it backward while still moving forward
- To find the middle
- To remove duplicates
- How much extra memory does the reverse-half method need?
- O(n)
- O(n²)
- O(1)
- O(log n)
- Which two earlier tools does this problem combine?
- Sorting and merging
- Hashing and cycles
- Insertion and deletion
- Finding the middle and reversing