本内容为LeetCode第二道题目:两数相加
# -*- coding: utf-8 -*- """ Created on Sun Mar 10 10:47:12 2019 @author: Administrator 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 """ ''' 定义链表的节点 ''' class ListNode: def __init__(self,val): self.val = val self.next = None class Solution: def addTwoNumber(self,l1,l2): ''' retutn the number of two number type l1: ListNode type l2: ListNode return : ListNode ''' answer = ListNode(0) temp = answer tempsum = 0 #存放临时变量 while True: if l1 != None: tempsum = tempsum + l1.val l1 = l1.next if l2 != None: tempsum = tempsum + l2.val l2 = l2.next temp.val = tempsum % 10 tempsum = tempsum // 10 #没有小数点 #条件的判断,只有当两个链表全部为空,而且当临时变量为0时结束 if l1 == None and l2 == None and tempsum == 0: break temp.next = ListNode(0) temp = temp.next return answer def printNum(self,l): while l!= None: num = l.val print(num) l = l.next if __name__ == '__main__': t1 = ListNode(3) t2 = ListNode(4) t3 = ListNode(2) t2.next = t1 t3.next = t2 n1 = ListNode(4) n2 = ListNode(6) n3 = ListNode(5) n2.next = n1 n3.next = n2 l1 = t3 l2 = n3 solution = Solution() answer = solution.addTwoNumber(l1,l2) solution.printNum(answer)