LeetCode 线性表篇:Add Two Number
一、题目描述
题目原文:
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.
两个单链表分别表示两个非负整数,表示形式为:数字个位—>数字十位—>数字百位........请以相同的单链表的形式返回两个数的和的结果
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
二、解题思路
此题不必按照咱们平时的早已根深蒂固的加法法则,这样考虑的话比较麻烦,就可以简单地看做两个单链表 node 相加,但是与加法不同的是从百位开始,遇到进位向右进位。
三、代码(来自//blog.csdn.net/lanchunhui/article/details/51119205)
class ListNode(object): def __init__(self, x): self.val = x self.next = None # 为链表添加新的元素 def addTail(l, node): if l.next is None: l.next = node else: p = l.next while p.next: p = p.next p.next = node class Solution(object): def addTwoNumbers(self, l1, l2): carrier = 0 x, y = l1.val, l2.val if x+y>=10: carrier = 1 l = ListNode(x+y-10) else: l = ListNode(x+y) while l1.next and l2.next: x, y = l1.next.val, l2.next.val if x+y+carrier>=10: addTail(l, ListNode(x+y+carrier-10)) carrier = 1 else: addTail(l, ListNode(x+y+carrier)) carrier = 0 l1 = l1.next l2 = l2.next # 以下两个 while 循环处理长度不一致的情况 while l1.next: if l1.next.val+carrier >= 10: addTail(l, ListNode(l1.next.val+carrier-10)) carrier = 1 else: addTail(l, ListNode(l1.next.val+carrier)) carrier = 0 l1 = l1.next while l2.next: if l2.next.val+carrier >= 10: addTail(l, ListNode(l2.next.val+carrier-10)) carrier = 1 else: addTail(l, ListNode(l2.next.val+carrier)) carrier = 0 l2 = l2.next # 还有进位 if carrier == 1: addTail(l, ListNode(1)) return l if __name__ == '__main__': print("----------------- start -----------------") l1_1 = ListNode(2) l1_2 = ListNode(4) l1_3 = ListNode(3) l1_1.next = l1_2 l1_2.next = l1_3 l2_1 = ListNode(5) l2_2 = ListNode(6) l2_3 = ListNode(4) l2_1.next = l2_2 l2_2.next = l2_3 l3_1 = Solution().addTwoNumbers(l1_1, l2_1) while l3_1 != None: print(l3_1.val) l3_1 = l3_1.next
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢