IniziaInizia gratis

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

Questo esercizio fa parte del corso

Data Structures and Algorithms in Python

Visualizza il corso

Istruzioni dell'esercizio

  • 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.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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
Modifica ed esegui il codice