สมมติว่าเรามีรายการองค์ประกอบ องค์ประกอบเหล่านี้ถูกจัดเก็บไว้ในรายการที่เชื่อมโยงเพียงอย่างเดียว เรายังมีค่า pos และค่า val เราต้องใส่ val ก่อน index pos ของลิงค์ลิสต์
ดังนั้น หากอินพุตมีค่าเท่ากับ nums =[1,5,3,6,8] pos =3 val =7 ผลลัพธ์จะเป็น [1,5,3,7,6,8]
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
-
ใหม่ :=สร้างโหนดรายการที่เชื่อมโยงด้วยค่าเดียวกับ val
-
ถ้า pos เหมือนกับ 0 แล้ว
-
ถัดไปของใหม่ :=list_head
-
กลับมาใหม่
-
-
อุณหภูมิ :=list_head
-
ในขณะที่ temp ไม่เป็นโมฆะและ pos ไม่เหมือนกับ 1 ให้ทำ
-
temp :=ถัดไปของอุณหภูมิ
-
pos :=pos - 1
-
-
ถัดไปของใหม่ :=ถัดไปของชั่วคราว
-
ถัดไปของอุณหภูมิ :=ใหม่
-
กลับ 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, ]