开始使用免费开始使用

在链表开头插入一个节点

在上一个练习中,您学习了如何实现 Node()LinkedList() 类。

在本练习中,您将为 insert_at_beginning() 方法编写代码,在链表开头添加一个新节点。

回顾 Node() 类:

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

本练习是课程的一部分

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
编辑并运行代码