Python中添加两个数字
假设我们有两个非空的链表。这两个链表表示两个非负整数。数字以逆序存储。它们的每个节点只包含一位数字。将这两个数字相加,并将结果作为链表返回。我们假设这两个数字不包含任何前导零,除了数字 0 本身。因此,如果数字是 120 + 230,则链表将是 [0 → 2 → 1] + [0 → 3 → 2] = [0 → 5 → 3] = 350。
为了解决这个问题,我们将遵循以下步骤:
- 取两个列表 l1 和 l2。将 head 和 temp 初始化为 null。
- c := 0
- 当 l1 和 l2 都是非空列表时
- 如果 l1 非空,则设置 a := 0,否则设置 a := l1.val
- 如果 l2 非空,则设置 b := 0,否则设置 b := l2.val
- n := a + b + c
- 如果 n > 9,则 c := 1,否则为 0
- node := 创建一个值为 n mod 10 的新节点
- 如果 head 为 null
head := node 且 temp := node
- 否则
- head.next := node,且 head := node
- l1 := l1 的下一个节点,如果 l1 存在
- l2 := l2 的下一个节点,如果 l2 存在
- 如果 c 不为零,则
- node := 值为 1 的新节点,head 的 next := node
- 返回 temp
示例(Python)
让我们看看下面的实现,以便更好地理解。
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = None
temp = None
c = 0
while l1 or l2:
if not l1:
a= 0
else:
a = l1.val
if not l2:
b=0
else:
b = l2.val
n = a +b + c
c = 1 if n>9 else 0
node = ListNode(n%10)
if not head:
head = node
temp = node
else:
head.next = node
head = node
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
if c:
node = ListNode(1)
head.next = node
return temp
ob1 = Solution()
l1 = make_list([0,2,1])
l2 = make_list([0,3,2])
print_list(ob1.addTwoNumbers(l1, l2))输入
[0,2,1] [0,3,2]
输出
[0,5,3]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP