如何合併兩個有序鍊錶

2021-09-29 05:18:04 字數 2233 閱讀 4892

【albb面試題】

題目:

把兩個有序的鍊錶合併成乙個有序的鍊錶,例如 1 -> 5 -> 6 和 2 -> 3 -> 7 -> 8,合併之後變成了 1 -> 2 -> 3 -> 5 -> 6 -> 7 -> 8。

解:

# 合併兩個有序鍊錶

class

node

:def

__init__

(self, data)

: self.data = data

self.

next

=none

class

link

:def

__init__

(self, head=

none

, tail=

none):

self.head = head

self.tail = tail

def(self, x)

: node = node(x)

if self.head is

none

: self.head = node

else

: self.tail.

next

= node

self.tail = node

link_a = link(

)link_b = link(

)for i in

range(1

,8):

if i &1:

continue

print

("合併前:"

)print

("link_a: "

, end=

" ")

p = link_a.head

while p:

print

(p.data, end=

"\t"

) p = p.

next

print()

p = link_b.head

print

("link_b: "

, end=

" ")

while p:

print

(p.data, end=

"\t"

) p = p.

next

defmerge

(link1, link2)

:# 合併函式

p1 = link1.head

p2 = link2.head

ifnot p1 or

not p2:

# 為空

return link1 if p1 else link2

while p1 and p2:

# 不為空

minnode = p1 if p1.data <= p2.data else p2

if p1 is link1.head and p2 is link2.head:

head = minnode

tail = minnode

else

: tail.

next

= minnode

tail = tail.

next

if p1.data < p2.data:

p1 = p1.

next

else

: p2 = p2.

next

if p1:

tail.

next

= p1

else

: tail.

next

= p2

newlink = link(

)# 生成新的鍊錶

newlink.head = head

newlink.tail = tail

return newlink

a = merge(link_a, link_b)

p = a.head

print()

print

("合併後: "

, end="")

while p:

print

(p.data, end=

"\t"

) p = p.

next

如何合併兩個有序鍊錶

已知兩個鍊錶head1和head2各自有序 例如公升序排列 請把他們合併成乙個鍊錶,要求合併後的鍊錶依然有序。class lnode def init self self.data none self.next none def constructlist start 方法功能 構造鍊錶 param...

合併兩個有序鍊錶

鍊錶的題目總是讓我很惆悵。動輒就會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...