Reverse a linked list

EasyTechnical
AmazonSoftware Development Engineer
334

Given the head of a singly linked list, reverse the list and return the reversed list. Implement both iterative and recursive solutions.

1 Answer

234
Top Answer

Iterative Solution

def reverseList(head: ListNode) -> ListNode:
    prev = None
    current = head

    while current:
        next_node = current.next  # Save next
        current.next = prev       # Reverse pointer
        prev = current            # Move prev forward
        current = next_node       # Move current forward

    return prev

Recursive Solution

def reverseList(head: ListNode) -> ListNode:
    # Base case
    if not head or not head.next:
        return head

    # Recursively reverse the rest
    new_head = reverseList(head.next)

    # Reverse the pointer
    head.next.next = head
    head.next = None

    return new_head

Time: O(n) for both Space: O(1) iterative, O(n) recursive (call stack)

LinkedListPro

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Amazon

View all