Algo-Sim › Linked Lists

Palindrome Linked List

Easy · Linked Lists · step through it in Java, Python and C++ on your own input

Find the middle with slow/fast, reverse the back half in place, then compare it with the front half: O(1) extra space.

Problem

Return true if the values of the singly linked list starting at head read the same forwards and backwards, and false otherwise.

Constraints

Edge cases to test

Follow-up questions

Should you restore the list?
Yes if the caller still uses it: reverse the back half again after comparing. Same O(n), O(1).
What is the simple version?
Copy values into an array and use two pointers: O(n) space.

Solution

Java

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;
    while (slow != null) {
        ListNode next = slow.next;
        slow.next = prev;
        prev = slow;
        slow = next;
    }
    ListNode left = head, right = prev;
    while (right != null) {
        if (left.val != right.val) return false;
        left = left.next;
        right = right.next;
    }
    return true;
}

Python

def is_palindrome(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    prev = None
    while slow:
        nxt = slow.next
        slow.next = prev
        prev, slow = slow, nxt
    left, right = head, prev
    while right:
        if left.val != right.val: return False
        left, right = left.next, right.next
    return True

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isPalindrome(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *prev = nullptr;
        while (slow != nullptr) {
            ListNode *next = slow->next;
            slow->next = prev;
            prev = slow;
            slow = next;
        }
        ListNode *left = head, *right = prev;
        while (right != nullptr) {
            if (left->val != right->val) return false;
            left = left->next;
            right = right->next;
        }
        return true;
    }
};

More Linked Lists problems