Add Two Numbers(from leetcode python 链表)

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

  

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def addTwoNumbers(self, l1, l2):
 9         """
10         :type l1: ListNode
11         :type l2: ListNode
12         :rtype: ListNode
13         """
14         if l1 == None: return l2
15         if l2 == None: return l1
16         // 使用dummyHead指向头结点,最后返回dummyHead.next
17         dummy_head = ListNode(0)
18         // 指针
19         pt = dummy_head
20         // 是否进位
21         carry = 0
22         while l1 and l2:
23             pt.next = ListNode((l1.val + l2.val + carry) % 10)
24             carry = (l1.val + l2.val + carry) / 10
25             pt = pt.next;
26             l1 = l1.next;
27             l2 = l2.next
28         if l1:
29             while l1:
30                 pt.next = ListNode((l1.val + carry) % 10)
31                 carry = (l1.val + carry) / 10
32                 pt = pt.next;
33                 l1 = l1.next
34             if carry == 1:
35                 pt.next = ListNode(1)
36             return dummy_head.next
37         if l2:
38             while l2:
39                 pt.next = ListNode((l2.val + carry) % 10)
40                 carry = (l2.val + carry) / 10
41                 pt = pt.next;
42                 l2 = l2.next
43             if carry == 1:
44                 pt.next = ListNode(1)
45             return dummy_head.next
46         if carry == 1:
47             pt.next = ListNode(1)
48         return dummy_head.next

 

posted @ 2018-06-25 09:54  Kkky  阅读(330)  评论(0编辑  收藏  举报