Hackbright Code Challenges

Remove Linked List Node: Solution

Remove Linked List Node: Solution

Problem

Remove Linked List Node

Whiteboard

Medium

Challenge

Easier

Concepts

Linked Lists

Download

remove-ll-node-solution.zip


We can do this cleverly by just re-assigning the data and next attributes to the next node in the series.

removellnode.py
def remove_node(node):
    """Given a node in a linked list, remove it.

    Remove this node from a linked list. Note that we do not have access to
    any other nodes of the linked list, like the head or the tail.

    Does not return anything; changes list in place.
    """

    # START SOLUTION

    if not node.next:
        raise ValueError("Cannot remove tail node")

    node.data = node.next.data
    node.next = node.next.next

The runtime of this is O(1).