在 Python 中的给定位置之前将新元素插入链表的程序
假设我们有一个元素列表;这些元素存储在一个单向链表中。我们还有一个值pos和值val。我们必须在链表的索引pos之前插入val。
因此,如果输入类似于nums=[1,5,3,6,8]pos=3val=7,那么输出将是[1,5,3,7,6,8]
示例
让我们看下面的实现来更好地理解
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, ]