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.
你可以假设这两个数值不是以0开头,也就是假设这两个数值是正常合法的

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

Definition for singly-linked list.

class ListNode(object):

def init(self, x):

self.val = x

self.next = None

class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p = 0
result = None
current = None
while True:
addValue = l1.val + l2.val + p
p = 0

        if addValue >= 10:
            addValue = addValue - 10
            p = 1

        node = ListNode(addValue)

        if result == None:
            result = node
            current = node
        else:
            current.next = node
            current = node

        l1 = l1.next
        l2 = l2.next

        if l1 == None or l2 == None:
            break

    if l1 == None and l2 == None:
        pass
    elif l1 == None or l2 == None:
        rest = None
        if l1 == None:
            rest = l2
        else :
            rest = l1

        while True:
            addValue = p + rest.val
            p = 0

            if addValue >= 10:
                addValue = addValue - 10
                p = 1

            node = ListNode(addValue)
            current.next = node
            current = node

            rest = rest.next
            if rest == None:
                break

    if p == 0:
        return result
    else:
        node = ListNode(p)
        current.next = node
        return result

看了答案才知道可以更简洁一些的 ~_~