数据结构单链表的前插法实现
单链表的前插法实现可以通过以下步骤进行:
-
创建一个新的节点,并将要插入的元素存储在新节点的数据域中。
-
将新节点的指针域指向原链表的头节点。
-
将原链表的头节点指向新节点。
具体代码实现如下所示:
class Node:def __init__(self, data):self.data = dataself.next = Nonedef insert_list_front(head, data):new_node = Node(data) # 创建新节点new_node.next = head # 将新节点的指针域指向原链表的头节点head = new_node # 将原链表的头节点指向新节点return head# 创建一个单链表
head = Node(1)
second = Node(2)
third = Node(3)head.next = second
second.next = third# 在单链表的前面插入一个新节点
head = insert_list_front(head, 0)# 打印插入节点后的链表
current = head
while current:print(current.data, end=" ")current = current.next
输出结果为:0 1 2 3,表示在原链表的前面插入了一个新节点0。