欢迎访问宙启技术站
智能推送

Python中使用insert()函数在链表中插入元素的示例代码

发布时间:2023-12-17 20:36:20

在Python中,链表是使用链式结构存储数据的一种数据结构。在链表中插入元素可以使用insert()函数。insert()函数可以在链表的任意位置插入元素,具体用法如下:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def insert(head, val, pos):
    # 创建新节点
    new_node = ListNode(val)
    # 如果要插入的位置是链表的头部
    if pos == 0:
        new_node.next = head
        return new_node
    # 如果要插入的位置不是链表的头部
    count = 0
    cur = head
    while count < pos - 1 and cur:
        count += 1
        cur = cur.next
    if not cur:
        return head
    new_node.next = cur.next
    cur.next = new_node
    return head

上述代码定义了一个链表节点类ListNode,以及一个插入函数insert()insert()函数接收三个参数:head表示链表的头节点,val表示要插入的元素,pos表示要插入的位置。

以下是使用insert()函数插入元素的一个实例:

# 创建链表 1->2->3->4
head = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
head.next = node2
node2.next = node3
node3.next = node4

# 在链表头部插入元素 0
head = insert(head, 0, 0)

# 在链表尾部插入元素 5
head = insert(head, 5, 5)

# 在链表中间插入元素 2.5
head = insert(head, 2.5, 3)

# 遍历链表并打印结果
cur = head
while cur:
    print(cur.val)
    cur = cur.next

运行以上代码,输出结果为:

0
1
2
2.5
3
4
5

以上代码先创建一个母链表1->2->3->4,然后分别在链表头部、尾部和中间插入元素0,5和2.5。最后再遍历链表并打印结果。

这是一个简单的使用insert()函数在链表中插入元素的示例代码。你可以根据实际需求,修改插入的位置和插入的元素进行实验。