双栈的python实现
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head1 ListNode类
# @param head2 ListNode类
# @return ListNode类
#
class Solution:
def addInList(self , head1 , head2 ):
# write code here
list1, list2 = [], []
if not head1:
return head2
if not head2:
return head1
while head1:
list1.append(head1.val)
head1 = head1.next
while head2:
list2.append(head2.val)
head2 = head2.next
temp = 0
cur = ListNode(0)
cur_next = None
while len(list1)!=0 and len(list2)!=0:
val1 = list1.pop()
val2 = list2.pop()
val_sum = val1 + val2 + temp
cur = ListNode(val_sum%10)
cur.next = cur_next
cur_next = cur
temp = val_sum//10
while len(list1)!=0:
val = list1.pop()
cur = ListNode((val+temp)%10)
temp = (val+temp)//10
cur.next = cur_next
cur_next = cur
while len(list2)!=0:
val = list2.pop()
cur = ListNode((val+temp)%10)
temp = (val+temp)//10
cur.next = cur_next
cur_next = cur
if temp==1:
cur = ListNode(temp)
cur.next = cur_next
cur_next = cur
return cur_next