[leetcode:python] 2.Add Two Numbers

来源:互联网 发布:淘宝上的装修付款方式 编辑:程序博客网 时间:2024/05/22 19:13

题目描述:
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

题意:
给定两个非空链表,存放的是非负整数。数值可逆序存放,每个节点只存放一个数。使两表相加并返回和表。

假设两个表的开头都没有0,除非这个表只包含0

代码:

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def addTwoNumbers(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        head = l1        carry = 0        while l1 and l2:            l1.val += (l2.val+carry)            carry = l1.val/10            l1.val = l1.val%10            pre = l1            l1 = l1.next            l2 = l2.next        if l2:            pre.next = l2            l2.val += carry            carry = l2.val/10            l2.val = l2.val%10            pre = l2        while carry:            if pre.next:                pre = pre.next                pre.val += carry                carry = pre.val/10                pre.val = pre.val%10            else:                pre.next = ListNode(carry)                carry = 0        return head
0 0