题目:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路1:
- 新建一个节点
head
指向合并后的链表,用aim
保存head
的地址。 - 若链表
a
和链表b
均不为空,则比较a
,b
的大小,head
节点指向min(a, b)
,min(a, b)
后移,head
后移,继续循环。 - 循环结束后,若
a
或者b
还有未合并的元素,则将其合并到head
后,返回aim.next
。
代码1:
# 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
"""
aim = head =ListNode(0)
while l1 and l2:
if l1.val < l2.val:
head.next = l1
l1 = l1.next
head = head.next
else:
head.next = l2
l2 = l2.next
head = head.next
if l1:
head.next = l1
if l2:
head.next = l2
return aim.next
思路2:
递归判断下一个较小的节点。
代码2:
# 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:
return l2
elif not l2:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2