# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'
https://oj.leetcode.com/problems/add-two-numbers/ You are given two linked lists representing two non-negative numbers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8 ===Comments by Dabay===
这道题没有要求不使用额外的空间。思路比较简单,就是逐个加起来的同时考虑进位。
那就在已有的空间上操作,主要是处理一些细节问题,如末尾有进位、两个数组不一样长等等。
我这里为了省事,当l1不够l2长的时候,用了额外的空间。
''' # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1 node1, node2, carry, end = l1, l2, 0, None
while node1 or node2:
if not node1:
node1 = ListNode(0)
end.next = node1
if not node2:
node2 = ListNode(0)
v = node1.val + node2.val + carry
carry = 0
if v >= 10:
v = v - 10
carry = 1
node1.val = v
end = node1
node1 = node1.next
node2 = node2.next
if carry:
end.next = ListNode(1)
return l1 def main():
root1 = ListNode(2)
root1.next = ListNode(4)
root1.next.next = ListNode(3)
root2 = ListNode(5)
root2.next = ListNode(6)
root2.next.next = ListNode(4)
s = Solution()
root = s.addTwoNumbers(root1, root2)
node = root
while node:
print "%s->" % node.val,
node = node.next
print "None" if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)

最新文章

  1. c++ 陷阱
  2. BZOJ4650: [Noi2016]优秀的拆分
  3. [技术学习]js继承
  4. HTML5的viewport使用
  5. jsonp与跨域
  6. 在android中使用achartengine来绘制各种图表
  7. nodeJs事件之监听移除事件
  8. iOS单例的两种实现
  9. c++11 : range-based for loop
  10. iframe和response.sendRedirect使用的问题
  11. 【详细贴】Ubuntu Linode搭建海外策略路由VPN IPSec+L2TP(一)
  12. C#之FileInfo的简单操作
  13. 使用WSL连接Docker for Windows
  14. SQLServer之删除触发器
  15. Shell获取指定时间
  16. 关于EmitMapper,映射配置
  17. WebRTC详解-zz
  18. 使用python登录CNZZ访问量统计网站,然后获取相应的数据
  19. [WebKit] JavaScriptCore解析--基础篇 (一)JSC与WebCore
  20. cloudermanager安装过程中出现W:GPG error错误 http://ppa.launchpad.net.trusty Release **** 4DF9B28CA252A784(图文详解)

热门文章

  1. Axure 快捷方式
  2. xml 解析 Xstream
  3. Mybatis基础入门 I
  4. WebResource.axd文件的配置和使用
  5. Delphi获取当前系统时间(使用API函数GetSystemTime)
  6. rsyslog 读日志文件 ,当rsyslog 中断时,也会丢数据
  7. 拓扑图弹力布局呈现Flickr图片搜索结果:智能创新
  8. Centos6.5升级gcc for qt5.3.1
  9. Struts2六、为应用指定多个配置文件
  10. SSH登陆服务器的简单命令