美文网首页
合并两个有序链表

合并两个有序链表

作者: hustyanye | 来源:发表于2019-07-21 09:21 被阅读0次

https://leetcode-cn.com/explore/interview/card/bytedance/244/linked-list-and-tree/1048/

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

一个个比较吧,遇到小的就放在新的链表中,在更新的时候注意几个问题:

  1. 记得保存新链表的头部用于返回!
  2. 遍历往后,l1或者l2会有剩余的,记得要遍历完整
    代码如下:
class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 and not l2:
            return None
        if not l1:
            return l2
        if not l2:
            return l1
        new_list = None
        new_list_head = None
        while l1 and l2:
            tmp = l1
            if l1.val > l2.val:
                tmp = l2
            if new_list:
                new_list.next = tmp
                new_list = new_list.next
            else:
                new_list = tmp
                new_list_head = tmp
            if l1.val>l2.val:
                l2 = l2.next
            else:
                l1 = l1.next
        if l1:
            while l1:
                new_list.next = l1
                new_list = new_list.next
                l1 = l1.next
        if l2:
            while l2:
                new_list.next = l2
                new_list = new_list.next
                l2 = l2.next
        return new_list_head

相关文章

  • leecode刷题(23)-- 合并两个有序链表

    leecode刷题(23)-- 合并两个有序链表 合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回。新...

  • 合并单链表

    合并两个有序链表非递归实现 合并两个有序链表递归实现

  • leetcode 链表 [C语言]

    21. 合并两个有序链表 合并两个有序链表 61. 旋转链表 (快慢指针) 61. 旋转链表 相关标签 : 链表 ...

  • ARTS-Week6 有序链表合并、DevOps、Json解析、

    Algorithm LeetCode原题链接: 合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回。新链...

  • 2018-12-26

    问题列表 合并两个有序链表 合并K个排序链表 合并区间 插入区间 问题与反馈 总结与收获 多个有序链表的合并,类似...

  • leetcode的题目21

    合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示...

  • Swift 合并两个有序链表 - LeetCode

    题目: 合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组...

  • LeetCode 21. 合并两个有序链表

    21. 合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成...

  • 刷leetCode算法题+解析(四)

    合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示...

  • Swift - LeetCode - 合并两个有序链表

    题目 合并两个有序链表 问题: 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节...

网友评论

      本文标题:合并两个有序链表

      本文链接:https://www.haomeiwen.com/subject/xgcmlctx.html