15 Jun 2024C++ / Python / TypeScriptEasy

Palindrome Linked List

Collected C++, Python, TypeScript solutions for palindrome linked list. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Palindrome Linked List. the solution files are available below.

solution files

  • C++ palindrome-linked-list/synced-solution.cpp
  • Python palindrome-linked-list/synced-solution.py
  • TypeScript palindrome-linked-list/synced-solution.ts

Solution files

Pythonpalindrome-linked-list/synced-solution.py
class ListNode:
    def __init__(self, val=class="syntax-number">0, next=None):
        self.val = val
        self.next = next

def isPalindrome(head: ListNode) -> bool:
    if not head or not head.next:
        return True

    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    prev = None
    while slow:
        next_temp = slow.next
        slow.next = prev
        prev = slow
        slow = next_temp

    while prev:
        if prev.val != head.val:
            return False
        prev = prev.next
        head = head.next

    return True
C++palindrome-linked-list/synced-solution.cpp
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if (!head || !head->next) return true;

        ListNode* slow = head;
        ListNode* fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }

        ListNode* prev = nullptr;
        while (slow) {
            ListNode* nextTemp = slow->next;
            slow->next = prev;
            prev = slow;
            slow = nextTemp;
        }

        while (prev) {
            if (prev->val != head->val) return false;
            prev = prev->next;
            head = head->next;
        }

        return true;
    }
};
TypeScriptpalindrome-linked-list/synced-solution.ts
function isPalindrome(head: ListNode | null): boolean {
    if (!head || !head.next) return true;

    let slow = head;
    let fast = head;
    while (fast && fast.next) {
        slow = slow.next!;
        fast = fast.next.next;
    }

    let prev: ListNode | null = null;
    while (slow) {
        const nextTemp = slow.next;
        slow.next = prev;
        prev = slow;
        slow = nextTemp;
    }

    while (prev) {
        if (prev.val !== head!.val) return false;
        prev = prev.next;
        head = head!.next;
    }

    return true;
}