博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Merge Two Sorted Lists
阅读量:6953 次
发布时间:2019-06-27

本文共 819 字,大约阅读时间需要 2 分钟。

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.

这题与 Two Numbers相似,注意的是存在长度不等,以及考虑使用dummy node作为结果的头元素,时间复杂度O(n+m),n为两条链表分别的长度。空间复杂度O(1).代码如下:

class Solution(object):    def mergeTwoLists(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        if not l1 and not l2:            return None        dummy = ListNode(-1)        cur = dummy        while l1 and l2:            if l1.val <  l2.val:                cur.next = l1                l1 = l1.next            else:                cur.next = l2                l2 = l2.next            cur = cur.next        cur.next = l1 if l1 else l2        return dummy.next

 

转载于:https://www.cnblogs.com/sherylwang/p/5426622.html

你可能感兴趣的文章
极限编程的12个实践原则
查看>>
javascript--返回顶部效果
查看>>
C# NamePipe使用小结
查看>>
ZooKeeper Watcher注意事项
查看>>
Linux下清理内存和Cache方法
查看>>
表单元素的外观改变(webkit and IE10)
查看>>
帆软报表学习笔记②——行转列
查看>>
redis应用场景:实现简单计数器-防止刷单
查看>>
两款开发辅助工具介绍
查看>>
python 文件的打开与读取
查看>>
基于ROS的运动识别
查看>>
python 之selectors 实现文件上传下载
查看>>
【hdu - 2568】ACM程序设计期末考试081230
查看>>
C语言基础(一)
查看>>
python处理xml中非法字符的一种思路
查看>>
itextSharp 附pdf文件解析
查看>>
solr6.0.0 + tomcat8 配置问题
查看>>
[leetcode-303-Range Sum Query - Immutable]
查看>>
LinkButton(按钮)
查看>>
leetcode Largest Rectangle in Histogram 单调栈
查看>>