Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมแทรกโหนดใหม่ใน Linked List ก่อนตำแหน่งที่กำหนดใน Python

แทรกค่า val ก่อน Index pos ใน Singly Linked List

ตัวอย่าง: nums=[1,5,3,6,8], pos=3, val=7 → [1,5,3,7,6,8]

ขั้นตอน

  1. สร้างโหนดใหม่ new = ListNode(val)
  2. ถ้า pos==0: new.next = head, คืน new
  3. เดินหาโหนดก่อนตำแหน่ง pos (คือ pos-1)
  4. new.next = temp.next; temp.next = new
  5. คืน 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
    new.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)  # Output: [1, 5, 3, 7, 6, 8, ]

อินพุต

[1,5,3,6,8], 3, 7

เอาต์พุต

[1, 5, 3, 7, 6, 8, ]