Python 中将新元素插入到给定位置之前的链接列表中的程序
pythonserver side programmingprogramming更新于 2025/12/18 2:52:17
假设我们有一个元素列表;这些元素存储在单链表中。我们还有一个值 pos 和值 val。我们必须在链接列表的索引 pos 之前插入 val。
因此,如果输入为 nums = [1,5,3,6,8] pos = 3 val = 7,则输出将为 [1,5,3,7,6,8]
为了解决这个问题,我们将遵循以下步骤 −
new := 创建一个值与 val 相同的链接列表节点
如果 pos 与 0 相同,则
next of new := list_head
返回 new
temp := list_head
当 temp 不为空且 pos 不等于 1 时,执行
temp := next of temp
pos := pos - 1
next of new := next of temp
next of temp := new
返回 list_head
示例
让我们看看下面的实现以便更好地理解
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
def solve(list_head, pos, val):
new = ListNode(val)
if pos == 0:
new.next = list_head
return new
temp = list_head
while temp and pos != 1:
temp = temp.next
pos -= 1
next = temp.next
temp.next = new
return list_head
nums = [1,5,3,6,8]
pos = 3
val = 7
list_head = make_list(nums)
list_head = solve(list_head, pos, val)
print_list(list_head)
输入
[1,5,3,6,8], 3, 7
输出
[1, 5, 3, 7, 6, 8, ]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

