MulaiMulai sekarang secara 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

Latihan ini adalah bagian dari kursus

Data Structures and Algorithms in Python

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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 dan Jalankan Kode