2. Add Two Numbers

来源:互联网 发布:喷绘用什么软件 编辑:程序博客网 时间:2024/06/01 07:21

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

翻译:两个链表作和,递归在这里并不很实用,涉及到NoneType has no attribute next

具体的创建链表等操作参看:

https://github.com/Sangewang/MacEnvPython/blob/master/LeetCode/2_AddTwoNum.py

class Solution(object):    def __init__(self):        self.flag = 0      def addTwoNumbers(self, l1, l2):        if l1 is None:            return l2        if l2 is None:            return l1        head = ListNode(-1)        p = head        while l1 or l2:            su = 0            if l1:                su += l1.val                l1 = l1.next            if l2:                su += l2.val                 l2 = l2.next            su += self.flag            self.flag =int(su/10)            tmp = ListNode(-1)            tmp.val = su%10            p.next = tmp            p = tmp        if self.flag == 1:            tmp = ListNode(self.flag)            p.next = tmp        return head.next


原创粉丝点击