Python 中在指定位置之前插入新元素到链表的程序
假设我们有一个元素列表;这些元素存储在单链表中。我们还有一个值 pos 和值 val。我们必须在链表的索引 pos 之前插入 val。
因此,如果输入类似于 nums = [1,5,3,6,8] pos = 3 val = 7,则输出将为 [1,5,3,7,6,8]
为了解决这个问题,我们将遵循以下步骤 -
new := 创建一个值为 val 的链表节点
如果 pos 等于 0,则
new 的 next := list_head
返回 new
temp := list_head
当 temp 不为空且 pos 不等于 1 时,执行
temp := temp 的 next
pos := pos - 1
new 的 next := temp 的 next
temp 的 next := 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, ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP