Reverse Linked List — LeetCode 206 Python Solution
EasyRecursionLinked List
- Problem
- #206
- Pattern
- Linked List
- Reading time
- 3 min
- Source
- leetcode.com
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
Python
# 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.nextComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the linked list |
| Space | O(1) auxiliary |
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
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and LeetCode 75.
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.