Reverse Linked List

easy · pointer reversal

You are given the head of a singly linked list. Reverse the list and return the head of the reversed list. Do it in place — do not build a new list or copy the values into an array. An empty list stays empty. The nodes are ListNode objects with val and next; the starter code defines the class. Constraints 0 ≤ nodes ≤ 5000; -5000 ≤ val ≤ 5000. Examples [1,2,3,4,5] → [5,4,3,2,1] [1,2] → [2,1] [] → []

Starter code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def reverse_list(head: ListNode | None) -> ListNode | None:
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

4 comments

Seed comments are jokes from BreakPy’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. Me at 2amCharacter joke · No posting date

    I renamed the function and everything broke. The function was load-bearing.

  2. AntyCharacter joke · No posting date

    I asked the hash for one shard. It gave me a lecture on consistency.

  3. AntyCharacter joke · No posting date

    I carried this test case uphill both ways. It still failed.

  4. InterviewerCharacter joke · No posting date

    Great approach. Now solve it without using the thing you just used.