EasyNo. 0206

Reverse Linked List — LeetCode 206 Python Solution

Topics
Recursion, Linked List
Reading time
3 min

The problem

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example

Input
head = [1,2,3,4,5]
Output
[5,4,3,2,1]

Python solution

PythonSolution
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        dummy = ListNode()
        curr = head
        while curr:
            next = curr.next
            curr.next = dummy.next
            dummy.next = curr
            curr = next
        return dummy.next

Complexity

Time
O(n)where n is the length of the linked list
Space · auxiliary
O(1)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 206. Reverse Linked List is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 206. Reverse Linked List?

LeetCode 206. Reverse Linked List is rated Easy on LeetCode.

What is the time complexity of LeetCode 206. Reverse Linked List?

The Python solution on this page runs in O(n), where n is the length of the linked list.

What is the space complexity of LeetCode 206. Reverse Linked List?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 206. Reverse Linked List cover?

LeetCode 206. Reverse Linked List is tagged Recursion and Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.