Leetcode在链接列表之间合并



我试图解决的问题如下:

您会得到两个链表:大小分别为n和m的list1和list2。将list1的节点从ath节点移到bth节点,并将list2放在它们的位置。

我已经将我的解决方案写成:

def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
count = 1
curr = list1
while count < a:
curr = curr.next
count += 1
curr2 = curr
while count < b:
curr2 = curr.next
count += 1
curr.next = list2
curr3 = list2
while curr3.next:
curr3 = curr3.next
curr3.next = curr2
return list1

我很难理解为什么它不起作用。我似乎找不到我的错误

两个小错误:

  1. curr2 = curr2.next替换curr2 = curr.next。我相信这只是你的一个拼写错误
  2. while count < b应该是while count <= b + 1。这是因为我们要删除从ab的所有节点,包括ab

def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
count = 1
curr = list1
while count < a:
curr = curr.next
count += 1
curr2 = curr
while count <= b + 1:
curr2 = curr2.next
count += 1
curr.next = list2
curr3 = list2
while curr3.next:
curr3 = curr3.next
curr3.next = curr2
return list1

相关内容

  • 没有找到相关文章

最新更新