Daily LeetCode 445. Add Two Numbers II

https://leetcode.com/problems/add-two-numbers-ii/

Medium

问题描述

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

1
2
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

题目分析

这一题与昨天的题目有一些不同,昨天的题目链表是从低位到高位排列的,而Add two numbers II是从高位向低位排列的,因此我们需要先将两个链表反转,再按昨天的解法处理,处理完之后,再将得到的链表反转输出。

如果不能对链表进行反转操作,我们可以通过栈来解决这个问题,分别遍历两个链表,将元素入栈,再对栈操作,采用与Add two numbers相同的解法,不同的是,构建链表时,我们需要采用头插法。

代码:

反转链表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def reverse_node(l):
if not l or not l.next:
return l
pre = None
while l:
tmp = l.next
l.next = pre
pre = l
l = tmp
return pre
res = point = ListNode(0)
extra = 0
l1 = reverse_node(l1)
l2 = reverse_node(l2)

while l1 != None or l2 != None:
l1_ele = l1.val if l1 != None else 0
l2_ele = l2.val if l2 != None else 0
sum = l1_ele + l2_ele + extra
extra = 1 if sum >= 10 else 0
point.next = ListNode(int(sum%10))
point = point.next
if l1 != None: l1 = l1.next
if l2 != None: l2 = l2.next

if extra:
point.next = ListNode(1)

return reverse_node(res.next)

栈:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 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
"""
stack1 = []
stack2 = []
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
res = ListNode()
extra = 0

while stack1 and stack2:
sum = stack1.pop() + stack2.pop() + extra
extra = 1 if sum >= 10 else 0
tmp = res
res = ListNode(int(sum % 10))
res.next = tmp

l = stack1 if stack1 else stack2

while l:
sum = l.pop() + extra
extra = 1 if sum >= 10 else 0
tmp = res
res = ListNode(int(sum % 10))
res.next = tmp

if extra:
tmp = res
res = ListNode(1)
res.next = tmp
return res.next