*445. Add Two Numbers II

Posted king-lps

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了*445. Add Two Numbers II相关的知识,希望对你有一定的参考价值。

1. 原始题目

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:

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

2. 题目理解

给定两个整数,求和。注意链表每个结点只放一个数字。高位在前。

 

3. 解题

思路:两个链表分别进栈,然后出栈时相加,注意设置一个临时变量用来存放进位。每次相加时应该是3个值相加:链表a+链表b+进位。

此外注意的是若最高为还有进位,则继续添加新节点。

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
 9         stack1 = []
10         stack2 = []
11 
12         newhead = ListNode(0)
13         while(l1):
14             stack1.append(l1.val)
15             l1 = l1.next
16         while(l2):
17             stack2.append(l2.val)
18             l2 = l2.next
19         p = 0            # 进位
20         while stack1 or stack2 or p:            # 注意这里别丢了 or p命令。如果有进位则还需创建新节点
21             temp = (stack1.pop() if stack1 else 0) + 22                    (stack2.pop() if stack2 else 0) + p         # 每次的和为两个链表的和+进位
23             p = temp//10                                       # 更新进位
24             
25             node = ListNode(temp%10)
26             node.next = newhead.next
27             newhead.next = node
28             
29         return newhead.next

 

验证:

 1 # 新建链表1
 2 listnode1 = ListNode_handle(None)
 3 s1 = [1,2,3,4,5,6,7,8]
 4 for i in s1:
 5     listnode1.add(i)
 6 listnode1.print_node(listnode1.head)
 7 
 8 # 新建链表2
 9 listnode2 = ListNode_handle(None)
10 s2 = [1,5,9,9,9]
11 for i in s2:
12     listnode2.add(i)
13 listnode2.print_node(listnode2.head)
14 
15 s = Solution()
16 head = s.addTwoNumbers(listnode1.head, listnode2.head)
17 listnode1.print_node(head)

1 2 3 4 5 6 7 8
1 5 9 9 9
1 2 3 6 1 6 7 7

 

以上是关于*445. Add Two Numbers II的主要内容,如果未能解决你的问题,请参考以下文章

445. Add Two Numbers II

445. Add Two Numbers II

*445. Add Two Numbers II

Leetcode445. Add Two Numbers II

leetcode 445. Add Two Numbers II

445. Add Two Numbers II - Medium