您的位置:首页 > 其它

Merge Two Sorted Lists - LeetCode

2015-02-04 20:17 281 查看

Merge Two Sorted Lists - LeetCode

题目:

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.

分析:

我选择的方式是直接进行比较,并且新建一个空间储存排序结果。注意的一点就是链表l1和l2会移动到为None的地步。

代码:

class Solution:
    # @param two ListNodes
    # @return a ListNode
    def mergeTwoLists(self, l1, l2):
        if not l1 and not l2:
            return None
            
            
        l4 =l = ListNode(0)
        
        while l1 and l2:
            if l1.val >= l2.val:
                l.next=  ListNode(l2.val)
                l2 = l2.next
            elif l1.val < l2.val:
                l.next = ListNode(l1.val)
                l1 = l1.next
            l = l.next  
        if not l1 and l2:
                l.next = l2
        if not l2 and l1:
                l.next = l1
        return l4.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: