[Leetcode][Python]21: Merge Two Sorted Lists
2024-08-26 06:15:54
# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com' 21: Merge Two Sorted Lists
https://oj.leetcode.com/problems/merge-two-sorted-lists/ 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. ===Comments by Dabay===
基本链表的操作。先做一个头节点,用两个指针来记录两个链表的位置。
比较两个链表的节点,把小的挂后边,之后移动指针。
最后,当一个链表已经比较完了之后,把另外一个链表中剩下的部分挂上。
''' # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
node = root = ListNode(0)
node1 = l1
node2 = l2
while node1 and node2:
if node1.val < node2.val:
node.next = node1
node1 = node1.next
else:
node.next = node2
node2 = node2.next
node = node.next
if node1:
node.next = node1
else:
node.next = node2
return root.next def main():
sol = Solution()
l1 = ListNode(1)
l2 = ListNode(2)
merged = sol.mergeTwoLists(l1, l2)
node = merged
while node:
print "%s ->" % node.val,
print "End" if __name__ == '__main__':
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)
最新文章
- Android 开发快速导引:Android程序框架【草】
- STL迭代器之一:偏特化
- 如何系统地自学一门Python 语言(转)
- butterknife简介及Generate ButterKnife Injections 不出现的问题解决
- 浅谈Java回调机制
- lamp环境的配置
- 数据库连接字符串大全 资料引用:http://www.knowsky.com/339545.html
- android中的selector背景选择器的用法
- Hibernate事务与并发问题处理(乐观锁与悲观锁)
- openoffice转换过程中遇到繁体字文档转换失败的问题
- win64安装及配置apache+php+mysql
- LUA 捕获模式 URL编码的例子解析
- Jmeter连接DB2/ORACLE/MYSQL数据库
- 免费的Lucene 原理与代码分析完整版下载
- python之MySQL MySQLdb 推荐使用姿势,解决中文乱码
- swust oj 971
- Random()种子数
- Mac 上有哪些比较有意思的小软件?
- [原创]Cadence Allegro小技巧之解决Out of date shapes问题
- 最大流Dinic算法
热门文章
- Oracle EBS-SQL (INV-2):检查帐户别名发放记录.sql
- docker网络-如何让外部网络访问容器资源
- C语言的本质(6)——位运算
- cdoj 排名表 拓扑排序 排名输出 贪心
- Asp.net SqlDataReader转成Datatable
- 【每天一个Linux命令】14. Linux中locate命令的用法
- UIViewController、UINavigationController与UITabBarController的整合使用
- 幸运大转盘-jQuery+PHP实现的抽奖程序
- SQL 数据类型、约束、索引及视图
- csharp中DateTime总结