Palindrome Linked List

Easy Linked ListTwo Pointers

Problem

Return true iff a singly linked list reads the same forwards and backwards.

Example 1 Input: head = [1,2,2,1] Output: true
Example 2 Input: head = [1,2] Output: false

Constraints

Approach — Two Pointers

This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(1) extra space.

Solution code

Python

class Solution:
    def isPalindrome(self, head):
        vals = []
        while head:
            vals.append(head.val)
            head = head.next
        return vals == vals[::-1]

Java

class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
        ListNode prev = null, curr = slow;
        while (curr != null) {
            ListNode n = curr.next;
            curr.next = prev;
            prev = curr; curr = n;
        }
        ListNode l = head, r = prev;
        while (r != null) {
            if (l.val != r.val) return false;
            l = l.next; r = r.next;
        }
        return true;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Palindrome Linked List interactively → ← All solutions