这题本来倒是不难,就是得搞明白是啥意思。这题是在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
if not l2:
return l1
stack = []
if l1.val >= l2.val:
l = l2
stack = [l1, l2.next]
else:
l = l1
stack = [l1.next, l2]
left = l
while True:
if not stack[0]:
left.next = stack[1]
return l
if not stack[1]:
left.next = stack[0]
return l
if stack[0].val >= stack[1].val:
left.next = stack[1]
left = left.next
stack[1] = stack[1].next
else:
left.next = stack[0]
left = left.next
stack[0] = stack[0].next