206. Reverse Linked List
Easy
Problem:
Reverse the linked list.
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
https://leetcode.com/problems/reverse-linked-list/
Solution:
Revursive 🔥
During the recursion, you keep attaching the previous list (prev
) to node.next
until node
becomes None
. When that happens, the linked list gets connected in reverse order due to backtracking. The prev
that is returned first ends up being the first node of the reversed linked list.
# 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: Optional[ListNode]) -> Optional[ListNode]:
def reverse(node: ListNode, prev: ListNode = None):
if not node:
return prev
next, node.next = node.next, prev
return reverse(next, node)
return reverse(head)
Iterative
Iteration takes about 70% less memory than recursion, which means it has a lower space complexity. Despite this, iteration tends to run slightly faster.
# 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: Optional[ListNode]) -> Optional[ListNode]:
node, prev = head, None
while node:
, node.next = node.next, prev
prev, node = node, next
return prev
Last updated