题目描述:
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.
题目分析:
这道题不难,但是有三点需要注意,尤其是第三点:
- 链表对应结点相加时增加前一个结点的进位,并保存下一个结点的进位;
- 两个链表长度不一致时,要处理较长链表剩余的高位和进位计算的值,例如:23+320=343;
- 如果最高位计算时还产生进位,则还需要添加一个额外结点,例如:5+5=10。
这道题我使用Python3来解决。Python与C++或者C语言不一样:它没有指针,所以不能通过指针来对同一个地址进行操作。因此,我不能像C++一样利用指针创建一个链表,而是只能创建一个list,每做完一位加法,就生成一个新的ListNode,并将这个新的ListNode与前面一个ListNode的next关联起来:result[-2].next=result[-1](下面代码中标黑部分)。这段代码比较冗长,但是时间复杂度是o(n)。
代码:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
jinwei=0
result=[]
count=0
while l1!=None and l2!=None:
sum=l1.val+l2.val+jinwei
if sum>9:
result.append(ListNode(sum-10))
jinwei=1
else:
result.append(ListNode(sum))
jinwei=0
l1=l1.next
l2=l2.next
if count!=0: #第一次是两个数个位相加,result列表中只有一个元素,所以不需要执行下面这条语句
result[-2].next=result[-1]
count=1
while l1!=None:
sum=l1.val+jinwei
if sum>9:
result.append(ListNode(sum-10))
jinwei=1
else:
result.append(ListNode(sum))
jinwei=0
l1=l1.next
result[-2].next=result[-1]
while l2!=None:
sum=l2.val+jinwei
if sum>9:
result.append(ListNode(sum-10))
jinwei=1
else:
result.append(ListNode(sum))
jinwei=0
l2=l2.next
result[-2].next=result[-1]
if jinwei==1:
result[-1].next=ListNode(jinwei)
return result[0]