两数相加
思路:因为数是用链表逆序表示的,因此先用列表将这些数提取出来。然后每一位对应相加大于10就进位,进位用carry表示。有两个特殊情况要考虑:(1)象5+5这种,两个数的位数一样,最后要增加一位。(2)象1+99这种,两个数的位数不一样,先将1+9相加跳出循环,后面是carry+9=10,又出现了一个进位。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
stack1 = []
stack2 = []
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
if len(stack1) > len(stack2):
stack1, stack2 = stack2, stack1
carry = 0
head = ListNode(-1)
p = head
while stack1:
tmp = stack1.pop(0) + stack2.pop(0) + carry
carry = tmp // 10
node = ListNode(tmp%10)
p.next = node
p = p.next
if not stack2 and carry == 1:
node = ListNode(1)
p.next = node
p = p.next
carry = 0
elif stack2:
while stack2:
tmp = stack2.pop(0) + carry
carry = tmp // 10
node = ListNode(tmp%10)
p.next = node
p = p.next
if carry == 1:
node = ListNode(1)
p.next = node
p = p.next
return head.next