stack的方式,把两个输入都用栈存起来,计算出的数值也用栈存起来
# 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
"""
if not l1:
return l2
if not l2:
return l1
carry = 0
stack1 = []
stack2 = []
q1 = l1
q2 = l2
while q1:
stack1.append(q1)
q1 = q1.next
while q2:
stack2.append(q2)
q2 = q2.next
stack3 = []
while stack1 and stack2:
sum = stack1.pop().val + stack2.pop().val + carry
he = sum % 10
carry = sum / 10
stack3.append(he)
while stack1:
sum = stack1.pop().val + carry
he = sum % 10
carry = sum / 10
stack3.append(he)
while stack2:
sum = stack2.pop().val + carry
he = sum % 10
carry = sum / 10
stack3.append(he)
if carry:
stack3.append(carry)
dummy = ListNode(0)
p = dummy
while stack3:
p.next = ListNode(stack3.pop())
p = p.next
return dummy.next
另外一种有趣的做法
# 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):
x1, x2 = 0, 0
while l1:
x1 = x1*10+l1.val
l1 = l1.next
while l2:
x2 = x2*10+l2.val
l2 = l2.next
x = x1 + x2
head = ListNode(0)
if x == 0: return head
while x:
v, x = x%10, x//10
head.next, head.next.next = ListNode(v), head.next
return head.next
网上的一种做法,很投机但很有趣
# 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):
x1, x2 = 0, 0
while l1:
x1 = x1*10+l1.val
l1 = l1.next
while l2:
x2 = x2*10+l2.val
l2 = l2.next
x = x1 + x2
head = ListNode(0)
if x == 0: return head
while x:
v, x = x%10, x//10
head.next, head.next.next = ListNode(v), head.next
return head.next
网友评论