"""
已知兩個鍊錶head1和head2各自有序(例如公升序排列),請把他們合併成乙個鍊錶,要求合併後的鍊錶依然有序。
"""class lnode:
def __init__(self):
self.data = none
self.next = none
def constructlist(start):
"""方法功能:構造鍊錶
:param start:
:return:
"""i = start
head = lnode()
tmp = none
cur = head
while i < 7:
tmp = lnode()
tmp.data = i
cur.next = tmp
cur = tmp
i += 2
return head
def printlist(head):
cur = head.next
while cur is not none:
print(cur.data, end=' ')
cur = cur.next
def merge(head1, head2):
"""方法功能:合併兩個公升序排列的單鏈表
:param head1: 鍊錶1
:param head2: 鍊錶2
:return: 合併後鍊錶的頭結點
"""if head1 is none or head1.next is none:
return head2
if head2 is none or head2.next is none:
return head1
cur1 = head1.next # 用來遍歷head1
cur2 = head2.next # 用來遍歷head2
head = none # 合併後鍊錶的頭結點
cur = none # 合併後的鍊錶在尾結點
# 合併後鍊錶的頭結點為第乙個結點元素最小的那個鍊錶的頭結點
if cur1.data > cur2.data:
head = head2
cur = cur2
cur2 = cur2.next
else:
head = head1
cur = cur1
cur1 = cur1.next
# 每次找到鍊錶剩餘結點最小值對應的結點連線到合併後鍊錶的尾部
while cur1 is not none and cur2 is not none:
if cur1.data < cur2.data:
cur.next = cur1
cur = cur1
cur1 = cur1.next
else:
cur.next = cur2
cur = cur2
cur2 = cur2.next
# 當遍歷完乙個鍊錶後把另外乙個鍊錶剩餘結點連線到合併後的鍊錶後邊
if cur1 is not none:
cur.next = cur1
if cur2 is not none:
cur.next = cur2
return head
if __name__ == '__main__':
head1 = constructlist(1)
head2 = constructlist(2)
print('head1:')
printlist(head1)
print('\nhead2:')
printlist(head2)
print('\n合併後的鍊錶')
head = merge(head1, head2)
printlist(head)
執行j結果如下:
head1:
1 3 5
head2:
2 4 6
合併後的鍊錶
1 2 3 4 5 6
如何合併兩個有序鍊錶
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 li...
合併兩個有序鍊錶
鍊錶的題目總是讓我很惆悵。動輒就會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...