原題描述:
將兩個排序鏈表合並為一個新的排序鏈表
樣例
給出 1->3->8->11->15->null,2->null, 返回 1->2->3->8->11->15->null。
題目分析:
依次從l1,l2表頭獲取節點,將小的添加到l3
源碼:
class Solution:
"""
@param two ListNodes
@return a ListNode
"""
def mergeTwoLists(self, l1, l2):
# write your code here
if l1 is None: return l2
if l2 is None: return l1
new = ListNode(0)
p1 = l1
p2 = l2
p3 = new
while p1 is not None and p2 is not None:
if p1.val < p2.val:
p3.next = p1
p1 = p1.next
else:
p3.next = p2
p2 = p2.next
p3 = p3.next
else:
if p1 is None:
p3.next = p2
else:
p3.next = p1
return new.next
