206. Reverse Linked List

Description

See: https://leetcode.com/problems/reverse-linked-list/

Solution

Standard reverse a linked list question. Implemented both iteratively and recursively.

Iterative

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        node = head
        prev = None
        while node != None:
            next_node = node.next
            node.next = prev
            prev = node
            node = next_node
        return prev

Time complexity: O(n)

Space complexity: O(1)

Recursive

Time complexity: O(n)

Space complexity: O(n) - recursive stack is the size of the linked list

Last updated