LeetCode——21. Merge Two Sorted Lists
合并两个有序的列表,使之产生一个有序的新列表
Description
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Examples
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Algorithm
# 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
"""
head = None
if l1 is None and l2 is None:
return head
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val <= l2.val:
head = ListNode(l1.val)
l1 = l1.next
else:
head = ListNode(l2.val)
l2 = l2.next
nexts = head
while l1 is not None or l2 is not None:
if l1 is None:
nexts.next = ListNode(l2.val)
l2 = l2.next
elif l2 is None:
nexts.next = ListNode(l1.val)
l1 = l1.next
elif l1.val <= l2.val:
nexts.next = ListNode(l1.val)
l1 = l1.next
else:
nexts.next = ListNode(l2.val)
l2 = l2.next
nexts = nexts.next
return head
Note
可以通过while循环迭代的方式实现此算法,首先判断两个列表是否为空,如果为空则直接返回空,或者直接返回不为空的列表。在两个列表不为空的情况下通过while循环,挨个比较两个列表的值,产生新的节点。
Algorithm-Recursive
还可以通过递归来实现该算法,递归在速度上和之前的迭代差不太多,快了大约2%,但是在空间占用上多了13%多,但是算法简单易懂。
# 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 l1 is None:
return l2
if l2 is None:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2