?LeetCode刷題實戰(zhàn)445:兩數(shù)相加 II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
示例

解題
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class?Solution:
????def?addTwoNumbers(self, l1:?ListNode, l2:?ListNode)?-> ListNode:
????????# 定義兩個棧用于存儲鏈表中的節(jié)點值
????????stack1, stack2 = [], []
????????# 最后的結(jié)果鏈表
????????ans = None
????????# 進位
????????carry = 0
????????while?l1:
????????????stack1.append(l1.val)
????????????l1 = l1.next
????????
????????while?l2:
????????????stack2.append(l2.val)
????????????l2 = l2.next
????????while?stack1 or?stack2 or?carry != 0:
????????????a = 0?if?not?stack1 else?stack1.pop()
????????????b = 0?if?not?stack2 else?stack2.pop()
????????????num = a + b + carry
????????????
????????????# res是余數(shù),就是要生成的新節(jié)點的值
????????????carry, res = divmod(num, 10)
????????????# cur_node是從低位到高位來建立新的節(jié)點,根據(jù)是出棧的值是低位先出棧來計算
????????????cur_node = ListNode(res)
????????????cur_node.next?= ans
????????????# ans左移
????????????ans = cur_node
????????
????????return?ans
LeetCode刷題實戰(zhàn)442:數(shù)組中重復(fù)的數(shù)據(jù)
