165 合併兩個排序鍊錶

2022-02-14 20:37:15 字數 1347 閱讀 3645

中文english

將兩個排序鍊錶合併為乙個新的排序鍊錶

樣例 1:

輸入: list1 = null, list2 = 0->3->3->null

輸出: 0->3->3->null

樣例2:

輸入: list1 = 1->3->8->11->15->null, list2 = 2->null

輸出: 1->2->3->8->11->15->null

輸入測試資料 (每行乙個引數)如何理解測試資料?

"""

definition of listnode

class listnode(object

): def __init__(self, val, next=none):

self.val =val

self.next =next

"""class

solution:

""" @param l1: listnode l1 is

the head of the linked list

@param l2: listnode l2

isthe head of the linked list

@return: listnode head of linked list

"""def mergetwolists(self, l1, l2):

# write your code here

#初始化乙個新的鍊錶,迴圈,比較l1.val 和 l2.val的大小。最後,如果那個鍊錶沒有取完,則直接丟進來

#初始化乙個新的鍊錶

dummay = listnode(0

)#如果不重新賦值tail尾巴的話,dummy一直在往後面鏈結新的節點,但是最終需要返回的是第乙個節點的next,所以需要乙個尾巴在後面不停的鏈結新節點,不停的更新指向

tail =dummay

while

l1 and l2:

if l1.val #每乙個賦予乙個新的節點

tail.next =listnode(l1.val)

l1 =l1.next

else

: tail.next =listnode(l2.val)

l2 =l2.next

tail =tail.next

#最後,如果還剩下l1,或者l2

ifl1:

tail.next =l1

else

: tail.next =l2

return

dummay.next

LintCode 165合併兩個排序鍊錶

題目鏈結 將兩個排序鍊錶合併為乙個新的排序鍊錶 樣例給出1 3 8 11 15 null,2 null,返回1 2 3 8 11 15 null。空間複雜度o 1 時間複雜度o m n m n分別為鍊錶l1和鍊錶l2的長度 definition of listnode class listnode ...

Lintcode 165 合併兩個排序鍊錶

我的程式碼如下 def mergetwolists self,l1,l2 if l1 none return l2 if l2 none return l1 res listnode none while l1 and l2 if l1.val l2.val print l1.val res l1 ...

合併兩個排序鍊錶

struct listnode class solution else while pstart1 null pstart2 null plast next pstart1 plast pend1 pend1 pend1 next pstart1 pend1 else plast next psta...