EasyNo. 0206
Reverse Linked List — LeetCode 206 Python Solution
- Pattern
- Linked List
- Topics
- Recursion, Linked List
- On study lists
- Blind 75, NeetCode 150, Grind 75 and LeetCode 75
- 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
# 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
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0092 | Reverse Linked List II | Medium |
| 0203 | Remove Linked List Elements | Easy |
| 0021 | Merge Two Sorted Lists | Easy |
| 0024 | Swap Nodes in Pairs | Medium |
| 0025 | Reverse Nodes in k-Group | Hard |
| 0019 | Remove Nth Node From End of List | Medium |
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.