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