合併兩個有序鍊錶,並返回乙個新的鍊錶。新煉表由前兩個鍊錶拼接而成。
example:input: 1->2->4, 1->3->4
output: 1->1->2->3->4->4
# definition for singly-linked list.
# class listnode(object):
# def __init__(self, x):
# self.val = x
# self.next = none
class solution(object):
def mergetwolists(self, l1, l2):
""":type l1: listnode
:type l2: listnode
:rtype: listnode
"""if not l1 and not l2: #l1和l2鍊錶均不存在
return none
if not l1: #l1鍊錶不存在
return l2
if not l2: #l2鍊錶不存在
return l1
while l2: #將l2鍊錶中的結點乙個乙個插入l1鍊錶中
l2_temp_node = listnode(l2.val) #將l2中結點賦值為新結點,鍊錶作為引數進行函式傳遞會隨函式進行動態變換
l1 = nodeinsert(l1,l2_temp_node)
l2 = l2.next
return l1
def nodeinsert(l1, node):
head_node = listnode(0) #頭指標
head_node.next = l1
moder_node = listnode(0) #指向當前結點的前乙個結點
if node.val < l1.val: #結點小於頭結點
node.next = l1
head_node.next = node
return head_node.next
moder_node = l1 #鍊錶往後移一位
l1 = l1.next
while l1: #遍歷判斷鍊錶
if l1.val>node.val: #判斷
node.next = l1
moder_node.next = node
return head_node.next
else: #往後遍歷鍊錶
moder_node=l1
l1=l1.next
moder_node.next = node #結點大於鍊錶中任意結點
return head_node.next
# definition for singly-linked list.
# class listnode(object):
# def __init__(self, x):
# self.val = x
# self.next = none
class solution(object):
def mergetwolists(self, l1, l2):
""":type l1: listnode
:type l2: listnode
:rtype: listnode
"""if not l1 and not l2: # l1和l2鍊錶均不存在
return none
if not l1: # l1鍊錶不存在
return l2
if not l2: # l2鍊錶不存在
return l1
l3 = listnode(0)
l3_head_node = l3
while l1 is not none and l2:
if l1.val <= l2.val:
l3.next = l1
l1 = l1.next
else:
l3.next = l2
l2 = l2.next
l3 = l3.next
if l1 is not none:
l3.next = l1
else:
l3.next = l2
return l3_head_node.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...