描述
假设链表中每一个节点的值都在 0 - 9?之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1?为 9->3->7,链表 2?为 6->3,最后生成新的结果链表为 1->0->0->0。
示例1
输入:
[9,3,7],[6,3]
返回值:
{1,0,0,0}
备注:
1≤n,m≤1061 \leq n, m \leq 10^61≤n,m≤106
0≤ai,bi≤90 \leq a_i, b_i \leq 90≤ai?,bi?≤9
栈
python的整除是//,/会出小数
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head1 ListNode类
# @param head2 ListNode类
# @return ListNode类
#
def inStack(stack: list, x: int):
stack.append(x)
def outStack(stack: list):
if len(stack) > 0:
return stack.pop(-1)
else:
return 0
class Solution:
def addInList(self , head1 , head2 ):
stack1, stack2, summ = [], [], []
tmp = 0
while head1 != None:
inStack(stack1, head1.val)
head1 = head1.next
while head2 != None:
inStack(stack2, head2.val)
head2 = head2.next
while len(stack1) > 0 or len(stack2) > 0:
x1 = outStack(stack1)
x2 = outStack(stack2)
x = x1 + x2 + tmp
tmp = x // 10
x = x % 10
inStack(summ, x)
if tmp > 0:
inStack(summ, tmp)
head = ListNode(outStack(summ))
result = head
while len(summ) > 0:
head.next = ListNode(outStack(summ))
head = head.next
return result
# write code here
|