Hackbright Code Challenges

Reverse Linked List: Solution

Reverse Linked List: Solution

Problem

Reverse Linked List

Whiteboard

Medium

Challenge

Easier

Concepts

Linked Lists

Download

rev-linked-list-solution.zip


This solution moves through the original list, duplicating each node and taking advantage of the __init__ method’s next argument to switch the direction of our pointers.

reversell.py
def reverse_linked_list(head):
    """Given LL head node, return head node of new, reversed linked list.

    >>> ll = Node(1, Node(2, Node(3)))
    >>> reverse_linked_list(ll).as_string()
    '321'
    """

    # START SOLUTION

    out_head = None
    n = head

    while n:
        out_head = Node(n.data, out_head)
        n = n.next

    return out_head