2、add two numbers(python)

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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:需要考虑进位
分三种情况:
两链表对应位均存在,则两数相加+前一列进位数
一链表对应位不存在,则另一链表对应位+前一位进位数
两链表对应位均不存在,则只+前一位进位数
注意:链表和结点的区别,ListNode是链表,链表新增加结点可采用新建链表拼接的方式,结点存在才有val
Runtime: 112 ms

#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):
        if not l1 :
            return l2
        if not l2:
            return l1
        dummy=ListNode(0)
        p=dummy
        p1=l1
        p2=l2
        count=0
        while  p1 or p2:
            if  p1 and p2 :
                s=p1.val+p2.val+count
                count=s/10
                p.next=ListNode(s%10)
                p=p.next
                p1=p1.next
                p2=p2.next
            elif not p1:
                s=p2.val+count
                p.next=ListNode(s%10)
                count=s/10
                p=p.next
                p2=p2.next
            elif not p2:
                s=p1.val+count
                p.next=ListNode(s%10)
                count=s/10
                p=p.next
                p1=p1.next
        if count>0:
            p.next=ListNode(count)
        return dummy.next

你可能感兴趣的:(leetcode)