[英]how do we organise a linked-list recurrence relation to merge two sorted linked list?
我已經編輯了代碼以合並下面的注釋(來自Trincot),唯一我仍然不清楚的是“l1.next = MergeTwoLists(l1.next,l2)”; 我仍然認為這是不對的-有什么想法可以修改嗎?
另外,我是否需要一個 while 語句,因為遞歸調用似乎已經在某種意義上循環了。
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
def MergeTwoLists(l1,l2):
prehead = ListNode(-1)
pointer_run = prehead
#Base Case
if not l1:
return l2
if not l2:
return l1
#Recurrence Relation
while l1 or l2:
if l1.val < l2.val:
pointer_run.next = l1
l1_temp = l1.val
l1.next= MergeTwoLists(l1.next,l2)
else:
pointer_run.next = l2
l2.next = MergeTwoLists(l1,l2.next)
return prehead.next
我沒有得到 output。
當l2.val == l1.val
時會發生這種情況。 這是代碼中的任何if
都沒有捕獲的情況,因此prehead.next
被執行。 但是next
屬性從未收到除初始值以外的值,我認為ListNode
構造函數將其設置為None
。
有以下問題:
最后一個if
應該是else
,因為您想在這兩個塊之一中捕獲上述情況。 由於這兩個塊( if
塊和 now else
塊)都以return
結尾,所以應該不可能return prehead.next
:可以刪除該語句。 這也意味着prehead
在其next
屬性被賦值后永遠不會被讀取,因此沒有任何作用。
return MergeTwoLists(l1.next,l2)
不正確。 您需要將返回值分配給l1.next
。 並且為了避免改變輸入列表,您應該首先創建一個值為l1
的新節點並分配給該新節點的next
屬性。 鏡像情況也是如此。
第一個基本情況不是必需的,因為它在下一個中涵蓋。
由於未給出ListNode
,我添加了將在更正代碼中使用的定義:
class ListNode:
# Constructor allows caller to optionally provide a next node
def __init__(self, val, nxt=None):
self.val = val
self.next = nxt
# A method to ease the iteration of all list values
def values(self):
yield self.val
if self.next:
yield from self.next.values()
# Define the representation of a list (e.g. for printing)
def __repr__(self):
return " → ".join(map(repr, self.values()))
# A class method to ease the creation of a list
@classmethod
def fromvalues(cls, *values):
head = None
for val in reversed(values):
head = cls(val, head)
return head
這是更正后的 function:
def MergeTwoLists(l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
return ListNode(l1.val, MergeTwoLists(l1.next, l2))
else:
return ListNode(l2.val, MergeTwoLists(l1, l2.next))
以下是運行它的方法:
l1 = ListNode.fromvalues(1, 2, 4)
l2 = ListNode.fromvalues(1, 3, 4)
result = MergeTwoLists(l1, l2)
print(result) # 1 → 1 → 2 → 3 → 4 → 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.