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

动态 未结 0 72
小小草
小小草 LV1 2023年9月23日 23:40 发表
Here's the code to create a new node, check whether the linked list has a head node, and point the next node of the new node to the head if it exists: ``` class LinkedList: def __init__(self): self.head = None self.tail = None def insert_at_beginning(self, data): # Create the new node new_node = Node(data) # Check whether the linked list has a head node if self.head: # Point the next node of the new node to the head new_node.next = self.head # Update the head to be the new node self.head = new_node else: # If there is no head, set the new node as both the head and tail self.head = new_node self.tail = new_node ``` Note that we also update the `tail` to be the new node if there is no head in the linked list.
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复