leetcode之Merge Two Sorted Lists

来源:互联网 发布:路由器封掉微信端口 编辑:程序博客网 时间:2024/06/08 15:47
这题本来倒是不难,就是得搞明白是啥意思。这题是在2个已经排好序的基础上排序的其实。所以最后的结果是要有排序的。代码如下:
# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass 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

0 0
原创粉丝点击