Giả sử chúng ta có một danh sách các phần tử; các phần tử này được lưu trữ trong một danh sách liên kết đơn lẻ. Chúng tôi cũng có một giá trị pos và giá trị val. Chúng ta phải chèn val trước vị trí chỉ mục của danh sách được liên kết.
Vì vậy, nếu đầu vào giống như nums =[1,5,3,6,8] pos =3 val =7, thì đầu ra sẽ là [1,5,3,7,6,8]
Để giải quyết vấn đề này, chúng tôi sẽ làm theo các bước sau -
-
new:=tạo một nút danh sách liên kết có giá trị giống như val
-
nếu pos giống 0 thì
-
tiếp theo của mới:=list_head
-
trả lại mới
-
-
temp:=list_head
-
trong khi tạm thời không phải là null và pos không giống như 1, hãy làm
-
temp:=next of temp
-
pos:=pos - 1
-
-
next of new:=next of temp
-
tiếp theo của tạm thời:=new
-
return list_head
Ví dụ
Hãy cùng chúng tôi xem cách triển khai sau để hiểu rõ hơn
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) Đầu vào
[1,5,3,6,8], 3, 7
Đầu ra
[1, 5, 3, 7, 6, 8, ]