1.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.
之前遇见过这道题以及变形题,可以直接求解,每次对应位置相加时需要考虑进位,当两个链表都为空时,需要考虑最后的进位,可能会时和的链表长度加一。
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
num = 0
flag = 0
head = None
tmp = None
while l1!=None or l2!=None:
num += flag
if l1!=None:
num += l1.val
l1 = l1.next
if l2!=None:
num += l2.val
l2 = l2.next
if num>=10:
num -= 10
flag = 1
else:
flag = 0
if head==None:
head = ListNode(num)
tmp = head
else:
node = ListNode(num)
tmp.next = node
tmp = node
if l1==None and l2==None and flag==1:
node = ListNode(1)
tmp.next = node
tmp = node
num = 0
return head
参考大神代码改了一下:很简洁
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
preHead = ListNode(0)
p = preHead
extra = 0
while l1!=None or l2!=None or extra!=0:
sum = (l1.val if l1!=None else 0) + (l2.val if l2!=None else 0) + extra
extra = int(sum / 10);
p.next = ListNode(sum % 10)
p = p.next
l1 = l1.next if l1!=None else l1
l2 = l2.next if l2!=None else l2
return preHead.next
注意在python3中除法变为真除法:
在Python3.0中变成真除法(无论任何类型都会保持小数部分,即使整除也会表示为浮点数形式)
因此需要将sum/10转换为int类型
python中条件表达式的语法
2.如果将两个输入链表变为反向输入 即从链表的头部作为数字的高位来实现链表加法
例如:(3 -> 4 -> 2) + (4 -> 6 -> 5) 输出 (8--0--7)
可以采用栈的方式,将链表顺序倒置,然后依次相加
可以先采用链表翻转的方式,实现链表的倒序