力扣445(java&python)-两数相加Ⅱ(中等)

题目:

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例1:

输入:l1 = [7,2,4,3], l2 = [5,6,4]

输出:[7,8,0,7]

示例2:

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[8,0,7]
示例3:

输入:l1 = [0], l2 = [0]
输出:[0]

提示:

链表的长度范围为 [1, 100]
0 <= node.val <= 9
输入数据保证链表代表的数字无前导 0
 

进阶:如果输入链表不能翻转该如何解决?

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

栈:定义两个栈,将两个链表的结点都推入栈中,然后从个位数开始出栈,当某一个栈为空时就补零继续计算,计算出每个位置的值以及进位,将计算的结果串成一个新链表。

java代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode() {}
 7  *     ListNode(int val) { this.val = val; }
 8  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 9  * }
10  */
11 class Solution {
12     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
13         //定义两个栈来存放两个链表的结点值
14         Deque<Integer> stack1 = new ArrayDeque<>();
15         Deque<Integer> stack2 = new ArrayDeque<>();
16 
17         //遍历链表将结点值存放进栈
18         while(l1 != null){
19             stack1.push(l1.val);
20             l1 = l1.next;
21         }
22         while(l2 != null){
23             stack2.push(l2.val);
24             l2 = l2.next;
25         }
26         //进位值
27         int carry = 0;
28         ListNode res = null;
29         while(!stack1.isEmpty() || !stack2.isEmpty() || carry != 0){
30             int sum = carry;
31             //如果当前栈为空,就补0继续计算
32             sum += stack1.isEmpty() ? 0 : stack1.pop();
33             sum += stack2.isEmpty() ? 0 : stack2.pop();
34             carry = sum / 10;
35             ListNode currNode = new ListNode(sum % 10);
36             currNode.next = res;
37             res = currNode;
38         }
39         return res;
40     }
41 }

 python3代码:

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, val=0, next=None):
 4 #         self.val = val
 5 #         self.next = next
 6 class Solution:
 7     def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
 8         list1 = []
 9         list2 = []
10         while l1:
11             list1.append(l1.val)
12             l1 = l1.next
13         
14         while l2:
15             list2.append(l2.val)
16             l2 = l2.next
17 
18         carry = 0
19         res = None
20         while list1  or list2  or carry != 0 :
21             sum = carry
22             sum += list1.pop() if list1 else 0
23             sum += list2.pop() if list2 else 0
24             carry = sum // 10
25             currNode = ListNode(sum % 10)
26             currNode.next = res
27             res = currNode
28         return res

posted on 2022-09-22 18:14  我不想一直当菜鸟  阅读(19)  评论(0编辑  收藏  举报