新手区 21. Merge Two Sorted Lists

沐芓李 · 2017年06月07日 · 最后由 沐芓李 回复于 2017年06月07日 · 1279 次阅读

题目描述

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.

把两个已经排序好的链表合并后返回一个新的有序链表。

原文地址

思路方法

1.构造一个新的链表,比较 l1 和 l2 指针指向的节点值,将小的放入新的链表,该链表指针后移。然后继续前面的操作,直到一个链表为空为止。剩下的链表全部链到新链表后面。

# 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 == None:
            return l2
        if l2 == None:
            return l1
        #新定义一个链表
        l = ListNode(0)
        temp = l
        while l1 != None and l2 != None:
            #因为l1和l2已经是排序好的了,就是相比较按顺序往新链表l里面存放
            if l1.val > l2.val:
                temp.next = l2
                l2 = l2.next
            else:
                temp.next = l1
                l1 = l1.next
            temp = temp.next
        #其中一个链表已经扫描结束,把另一个链表直接存放在后面就可以了
        if l1 == None:
            temp.next = l2
        if l2 == None:
            temp.next = l1

        return l.next

2.可以采用递归方式,我没有实践 2,借鉴别人的,参考地址

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        ret = ListNode(0)
        head = ret
        while l1 != None and l2 != None:
            if l1.val > l2.val:
                ret.next = l2
                l2 = l2.next
            else:
                ret.next = l1
                l1 = l1.next
            ret = ret.next

        if l1 == None:
            ret.next = l2

        if l2 == None:
            ret.next = l1

        return head.next

知识点

这里用到了链表的数据结构,可是已经实现了,并没有自己实现

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 2 条回复 时间 点赞
沐芓李 代码入门 中提及了此贴 06月07日 14:18

LeetCode?

magicyang 回复

恩呢

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册