在 Python 中的链表之间合并的程序
假设我们有两个长度分别为m和n的链表L1和L2,我们也有两个位置a和b。我们必须从第a个节点到第b个节点的L1中删除节点,并在它们之间合并L2。
所以,如果输入像L1=[1,5,6,7,1,6,3,9,12]L2=[5,7,1,6]a=3b=6,那么输出将是[1,5,6,5,7,1,6,9,12]
示例
让我们看看以下实现以获得更好的理解-
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(L1, L2, a, b): head2 = temp = L2 while temp.next: temp = temp.next tail2 = temp count = 0 temp = L1 end1, start3 = None, None while temp: if count == a-1: end1 = temp if count == b+1: start3 = temp break temp = temp.next count += 1 end1.next = head2 tail2.next = start3 return L1 L1 = [1,5,6,7,1,6,3,9,12] L2 = [5,7,1,6] a = 3 b = 6 print_list(solve(make_list(L1), make_list(L2), a, b))
输入
[1,5,6,7,1,6,3,9,12], [5,7,1,6], 3, 6输出结果
[1, 5, 6, 5, 7, 1, 6, 9, 12, ]