開始使用免費開始

在連結串列開頭插入節點

在上一個練習中,你學會如何實作 Node()LinkedList() 類別。

在這個練習中,你要為 insert_at_beginning() 方法準備程式碼,將新節點插入到連結串列的開頭。

回憶一下 Node() 類別:

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

本練習屬於課程

Data Structures and Algorithms in Python

檢視課程

練習說明

  • 建立新的節點。
  • 檢查連結串列是否有 head 節點。
  • 如果連結串列有 head 節點,將新節點的 next 指向 head

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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
編輯並執行程式碼