Get startedGet started for free

Inserting a node at the beginning of a linked list

In the previous exercise, you learned how to implement a Node() and LinkedList() class.

In this exercise, you will prepare the code for the insert_at_beginning() method to add a new node at the beginning of a linked list.

Recall the Node() class:

class Node:
  def __init__(self, data):
    self.data = data
    self.next = None

This exercise is part of the course

Data Structures and Algorithms in Python

View Course

Exercise instructions

  • Create the new node.
  • Check whether the linked list has a head node.
  • If the linked list has a head node, point the next node of the new node to the head.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

def insert_at_beginning(self, data):
    # Create the new node
    new_node = ____(data)
    # Check whether the linked list has a head node
    if self.____:
      # Point the next node of the new node to the head
      new_node.___ = self.____
      self.head = new_node
    else:
      self.tail = new_node      
      self.head = new_node
Edit and Run Code