1.问题描述:
将两个排序链表合并为一个新的排序链表。
2.样例:
给出 1->3->8->11->15->null
,2->null
, 返回 1->2->3->8->11->15->null
。
3.代码:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: l1: ListNode l1 is the head of the linked list
@param: l2: ListNode l2 is the head of the linked list
@return: ListNode head of linked list
"""
def mergeTwoLists(self, l1, l2):
# write your code here
if l1 is None:
return l2
elif l2 is None:
return l1
else:
if l1.val <= l2.val:
newhead=p=l1
l1=l1.next
else:
newhead=p=l2
l2=l2.next
while l1 and l2:
if l1.val <= l2.val:
p.next=l1
l1=l1.next
p=p.next
else:
p.next=l2
l2=l2.next
p=p.next
if l1:
p.next=l1
if l2:
p.next=l2
return newhead
本题思路并不复杂,代码看起来稍有点多。主要分为几种情况:
1)l1或l2中如果有None,则直接返回另外一个链表即可
2)需要判断两个链表的头结点的大小,确定新链表的头结点
3)当某个链表的数已经全部加到新链表中后,把另外一个链表剩余的数加入即可