[英]LeetCode problem 21: Merge Two Sorted Lists - the first list I create is never processed
[英]python linked list leetcode problem 21 Merge Two Sorted Lists
我有一個關於 python 中鏈表的快速問題。 在下面顯示的解決方案代碼中,當我嘗試合並兩個已排序的鏈表時。 我對包含的 if 和 elif 語句的條件感到困惑。 例如,如果 l1 不為空而 l2 為空,我想將 l1 中的其余 3 個元素添加到我的新鏈表中,但代碼顯示 l1 和 tail 未更新,所以它不只是添加一個3?
我的另一個問題是關於返回 head.next。 返回是否會自動將每個節點從 head.next 返回到 null ptr? 謝謝!
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode()
tail = head
while l1 and l2:
if l1.val < l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
if l1:
tail.next = l1
#why don't I update l1 and tail
elif l2:
tail.next = l2
#why don't I update l2and and tail
return head.next
#does returning head.next return every single value from head.next to null?
好吧,您正在使用鏈表,因此如果您指向一個特定節點並且該節點在其下一個節點中有更多節點,那么您將獲得所有節點。
那么這里有什么問題呢?
嗯,其實沒什么。 你正在返回head -> next
,所以基本上你正在返回整個鏈表。 如果您像這樣遍歷列表:
merged_list = solution.mergeTwoLists(lst1, lst2)
while merged_list:
print(str(merged_list.val), end = ' -> ')
merged_list = merged_list.next
print(merged_list)
例如,如果您有以下鏈表lst1
和lst2
定義如下:
lst1 = ListNode(1)
lst1.next = ListNode(6)
lst1.next.next = ListNode(3) # So lst1 is basically 1 -> 6 -> 3 -> None
lst2 = ListNode(4)
lst2.next = ListNode(5)
lst2.next.next = ListNode(2) # And lst2 is basically 4 -> 5 -> 2 -> None
然后你會得到最終結果:
1 -> 4 -> 5 -> 2 -> 6 -> 3 -> None
這正是您在代碼中應用的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.