【LeetCode每天一题】Add Two Numbers(两链表相加)

  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.

Example:                       Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)                       Output: 7 -> 0 -> 8                                Explanation: 342 + 465 = 807.

  思路:链表相加和字符串相加挺相似得,先构建一个哨兵节点。每次当前两个节点值相加之后再判断溢出标志位是否为1,有的话在加上溢出位的数据,然后判断得到得总和是否有溢出,溢出则将溢出标志位设置为1,并将总和减去10,然后构建一个节点将值设置为总和的值,并将哨兵next指针指向新建得节点,然后更新哨兵得指针让其直到刚才新建得节点。 依此重复。 直到最后一个节点都建造完毕。 这里有一点需要特别注意的是,当两个链表同时完毕之后,但最后两个变量加起来有溢出。需要在最后进行判断来防止这种情况出现。

  时间复杂度为O(n+m) (m, n分别为两个链表的长度), 空间复杂度为O(n+m) (m, n分别为两个链表的长度)。

步骤如下:

                                     

  代码:

 1 class Solution(object):
 2     def addTwoNumbers(self, l1, l2):
 3         """
 4         :type l1: ListNode
 5         :type l2: ListNode
 6         :rtype: ListNode
 7         """
 8         if not l1 or not l2:                # 如果任意一个链表为空,直接返回另一个链表
 9             return l1 if l1 else l2
10         Res_Node = cur = ListNode(0)
11         flow = 0                            # 溢出标志位
12         while l1 or l2:
13             tem_1 = l1.val if l1 else 0     # 当L1为空时, 返回0
14             tem_2 = l2.val if l2 else 0     # L2 为空时,返回0
15             tem_sum = tem_1 + tem_2         # 将两个结果进行相加
16             if flow > 0:                     # 判断溢出位是否为1
17                 tem_sum += flow              
18                 flow = 0
19             if tem_sum >= 10:                # 总和是否大于等于10
20                 flow = 1
21                 tem_sum -= 10
22             cur.next = ListNode(tem_sum)     # 新建一个节点存储当前和的值
23             cur = cur.next
24             l1 = l1.next if l1 else None     # 将L1和L2指向下一个位置,如果下一个位置为空时,返回None
25             l2 = l2.next if l2 else None
26         if flow > 0:                         # 判断最后是否存在溢出。
27             cur.next = ListNode(flow)
28         return Res_Node.next                  # 返回新构建的链表的头节点
原文地址:https://www.cnblogs.com/GoodRnne/p/10603515.html