我写了这样一个解决方案 merge two sorted list
合并两个已排序的链表并将其作为新列表返回。应该通过将前两个列表的节点拼接在一起来制作新列表。
例子:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
我的解决方案:
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution3:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
Plan:
Compare l1 and l2 and merge the remainders
"""
head = ListNode(0) #create head to hold
l3 = ListNode(0)
head.next = l3
while l1 and l2: #assert both exist
if l2.val < l1.val:
l3 = l2 #build l3's node
l2 = l2.next #this is i++
else:
l3 = l1
l1 = l1.next
l3 = l3.next #find the next to build
if l1:
l3 = l1
if l2:
l3 = l2
return head.next
但得到错误的答案
输入
[1,2,4] [1,3,4]
输出
[0]
预期的
[1,1,2,3,4,4]
我检查过但找不到我的逻辑有任何问题。
你能帮我一下吗?
波斯汪
Qyouu
30秒到达战场
相关分类