(適合初學者)合併兩個有序鍊錶

2021-10-10 01:37:53 字數 1671 閱讀 4055

示例1:

輸入:1->2->4, 1->3->4

輸出:1->1->2->3->4->4

限制:0 <= 鍊錶長度 <= 1000

這個題目主要就是說明有兩個鍊錶,每個鍊錶都是排好的順序,想要把這個兩個鍊錶放到乙個鍊錶進行排序。一起看看下面的解析**(學過資料結構的同學,應該會很快能夠理解):

class

listnode

:#定義乙個類,這個類主要是定義結點,

def__init__

(self, x)

: self.val = x#傳入的值,也就是結點的值

self.

next

=none

#下乙個取值,一定要後面的函式物件建立和呼叫才能更好的了解

class

solution

:def

mergetwolists

(self, l1, l2)

:"""

:type l1: listnode

:type l2: listnode

:rtype: listnode

"""newhead = listnode(0)

pre = newhead

while l1 and l2:

if l1.val < l2.val:

pre.

next

= l1

l1 = l1.

next

else

: pre.

next

= l2

l2 = l2.

next

pre = pre.

next

if l1:

pre.

next

= l1

elif l2:

pre.

next

= l2

return newhead.

next

###一定要看下面的內容你會很快就能理解到位的。

# 有序鍊錶

head1 = listnode(2)

n1 = listnode(3)

n2 = listnode(4)

n3 = listnode(9)

head1.

next

= n1

n1.next

= n2

n2.next

= n3

head2 = listnode(3)

m1 = listnode(5)

m2 = listnode(7)

m3 = listnode(8)

head2.

next

= m1

m1.next

= m2

m2.next

= m3

s = solution(

)res = s.mergetwolists(head1, head2)

while res:

print

(res.val)

res = res.

next

執行結果:

合併兩個有序鍊錶

鍊錶的題目總是讓我很惆悵。動輒就會runtime error。比如這題,額外用了乙個節點的空間來儲存頭節點。我很不情願多用這個空間,不過貌似不行。貌似不行,實際可行,見附錄。把頭節點提出迴圈 實現類 class solution else if l1 null p next l1 if l2 nul...

合併兩個有序鍊錶

三個指標乙個儲存la鍊錶 乙個儲存lb鍊錶,乙個指向新的鍊錶。鍊錶的插入,兩個指標,乙個是head,乙個指向head後面的鏈,新插入的元素位於head後面。執行該 自己外加上class類。static class node public static void main string args st...

合併兩個有序鍊錶

將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。示例 輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4思路 很簡單就是二路歸併的思想,時間複雜度o n definition for singly linked list.struct listno...