3 回答
TA贡献1811条经验 获得超4个赞
您l3应该确定应附加下一个节点的位置,因此
l3 = head
您需要将给定 (l1或l2)列表之一的头部附加到l3,但您不需要。
在添加节点之后,您需要同时推进源列表的头指针 ( l1or l2) 和目标列表的尾指针 ( l3):
while l1 and l2: #assert both exist
if l2.val < l1.val:
l3.next = l2 #append new node to the resulting list
l2 = l2.next #and skip it in the source list
else:
l3.next = l1
l1 = l1.next
l3 = l3.next #find the next to build
TA贡献1786条经验 获得超11个赞
这是我的解决方案
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def insert(self,el):
Node = self
while Node:
if Node.next==None:
Node.next = ListNode(el)
break
else:
Node =Node.next
def prin(node):
while node:
if node.next:
print(node.val,end='-> ')
else:
print(node.val)
node = node.next
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
"""
Plan:
Compare l1 and l2 and merge the remainders
"""
_node = None
if l1.val<l2.val:
_node = ListNode(l1.val)
l1 =l1.next
else:
_node = ListNode(l2.val)
l2=l2.next
l3 = _node
while l1 and l2: #assert both exist
if l2.val < l1.val:
l3.insert(l2.val)
l2 = l2.next
else:
l3.insert(l1.val)
l1 = l1.next
while l1:
l3.insert(l1.val)
l1 =l1.next
while l2:
l3.insert(l2.val)
l2 = l2.next
return l3
node1= ListNode(1)
node1.insert(2)
node1.insert(4)
node2 = ListNode(1)
node2.insert(3)
node2.insert(4)
solved_list = mergeTwoLists(node1,node2)
solved_list.prin()
TA贡献1828条经验 获得超6个赞
你永远改变表结构(有任何不分配next在循环S),你只是移动l1,l2以及l3沿输入列表。
然后您返回head.next,它仍然是您首先分配给它的节点。
由于您使用哨兵节点的方法使代码比不使用更简单,因此我将其保留在此处:
def merge(l1, l2):
first = ListNode(0)
# 'here' is where we link in the nodes.
here = first
while l1 and l2:
# Pick the next node from the inputs.
# Note that this has the same effect as assigning
# to 'first.next' on the first iteration, when 'first' and 'here'
# refer to the same object.
if l1.val < l2.val:
here.next = l1
else:
here.next = l2
# Move along to the last node we picked.
here = here.next
# Grab the rest.
if l1:
here.next = l1
else:
here.next = l2
return first.next
添加回答
举报