LeetCode Add Two Numbers
2015-12-11 22:07
363 查看
LeetCode解题之Add Two Numbers
原题
定义这样的一个链表,链表的每个节点都存有一个0-9的数字,把链表当成数字,表头为高位,表尾为地位。如1->2->3表示321,现在要对两个这样的链表求和。注意点:
数字的高低位,应该从从地位向高位进位
有多种情况要考虑,如链表长度是否相等、是否进位等
例子:
输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8
解题思路
把两个链表当成是相同长度的,短的那个想象成后面都是0;如果进位的话,在初始化下一个节点的时候将其赋值为1即可,所以在计算当前节点的值时要加上自己本来的值。AC源码
class ListNode(object): def __init__(self, x): self.val = x self.next = None # Define this to check if it works well def myPrint(self): print(self.val) if self.next: self.next.myPrint() class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ result = ListNode(0); cur = result; while l1 or l2: cur.val += self.addTwoNodes(l1, l2) if cur.val >= 10: cur.val -= 10 cur.next = ListNode(1) else: # Check if there is need to make the next node if l1 and l1.next or l2 and l2.next: cur.next = ListNode(0) cur = cur.next if l1: l1 = l1.next if l2: l2 = l2.next return result def addTwoNodes(self, n1, n2): if not n1 and not n2: # This cannot happen, ignore it None if not n1: return n2.val if not n2: return n1.val return n1.val + n2.val if __name__ == "__main__": list = ListNode(9) list.next = ListNode(8) print(Solution().addTwoNumbers(list, ListNode(1)).myPrint())
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- [C/C++]反转链表
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例