[英]LeetCode problem 21: Merge Two Sorted Lists - the first list I create is never processed
我创建了两个链表,但第一个链表从未在mergeTwoList()
中处理:
class ListNode:
def __init__(self,data):
self.data = data
self.next = None
def mergeTwoList(l1: ListNode, l2: ListNode) -> ListNode:
cur = ListNode(0)
ans = cur
while(l1 and l2):
print("in loop 1 and 2 :")
if(l1.data > l2.data):
print("in if 1 :")
cur.next = l2
l2 = l2.next
else:
print("in if 2 :")
cur.next = l1
l1 = l1.next
cur = cur.next
while(l1):
print("in loop 1 :")
cur.next = l1
l1 = l1.next
cur = cur.next
while(l2):
print("in loop 2 :")
cur.next = l2
l2 = l2.next
cur = cur.next
return ans.next
if __name__ == "__main__":
l1_1 = ListNode(1)
l1_2 = ListNode(2)
l1_3 = ListNode(3)
l1_1.next = l1_2
l1_2.next = l1_3
l2_1 = ListNode(4)
l2_2 = ListNode(5)
l2_3 = ListNode(6)
l2_1.next = l2_2
l2_2.next = l2_3
while(l1_1 is not None):
print(l1_1.data)
l1_1 = l1_1.next
print("<------>")
answer = mergeTwoList(l1_1,l2_1)
while(answer is not None):
print(answer.data)
answer = answer.next
结果:
1
2
3
<----->
在循环 2 中:
在循环 2 中:
在循环 2 中:
4
5
6
它永远不会通过第一个while
条件 --> while(l1 and l2)
我怀疑它与 Python 中的 class 调用有关,但不确定。 任何帮助将不胜感激。 如果我将此方法放在 class 中,然后在外部调用它,它就可以工作。 但是上面的代码失败了。
在你的第一个循环结束时:
while(l1_1 is not None):
print(l1_1.data)
l1_1 = l1_1.next
l1_1
是None
,并传递给您的 function mergeTwoList
, l1 是None
,因此未输入 function 中的第一个循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.