原题描述:
将两个排序链表合并为一个新的排序链表
样例
给出 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