2018年9月9日
#2. 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.
样例:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
问题分析:
本题难度为Medium!已给出的函数定义为:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
其中l1和l2分别是类ListNode的实例,返回值也是类ListNode的实例;
本题的目标是很简单的两数相加的链表实现,算法(伪代码)如下:
将当前节点初始化为返回列表哑结点(值val任意)
将进位carry初始化为0
声明p和q分别为l1和l2
遍历p和q直到到达p和q的尾部:
设x为结点p的值,若p为空,则x值为0
设y为结点q的值,若q为空,则y值为0
设sum=carry+x+y
更新carry的值为sum的10位上的数值
创建一个数值为sum mod 10的新结点,并将其设置为当前结点的下一个结点
更新当前结点为下一个结点
更新p和q为下一个结点,若为空,则不变
最后检查carry是否为1,如是,则需要在当前结点后增添一个值为1的结点
返回哑结点的下一个结点
具体的python代码实现如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
curr = res
p = l1
q = l2
carry = 0 #初始进位1或0
while p!=None or q!=None:
x = p.val if p!=None else 0
y = q.val if q!=None else 0
sum = carry + x + y
carry = sum//10 #取整
curr.next = ListNode(sum%10)
curr = curr.next
if p!=None:
p = p.next
if q!=None:
q=q.next
if carry>0:
curr.next = ListNode(1)
return res.next