力扣 - 445. 两数相加 II

时间:2023-03-09 03:16:32
力扣 - 445. 两数相加 II

题目

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

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

  • 如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7

思路

对于逆序处理得问题,我们首先要想到使用栈来解决,先将要处理的元素入栈,再出栈一个一个处理即可。这一题就是要从最后一位往前加得,如果大于10还要进位,将两个链表入栈,再pop元素来处理,结果大于1,通过carry变量来记录在下一位加1

代码实现

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//用LinkedList来当作栈
LinkedList<ListNode> list1 = new LinkedList<>();
LinkedList<ListNode> list2 = new LinkedList<>();
//头指针
ListNode newHead = new ListNode(-1);
newHead.next = null; //链表元素入栈
while (l1 != null) {
list1.push(l1);
l1 = l1.next;
}
while (l2 != null) {
list2.push(l2);
l2 = l2.next;
} //用来记录进位得
int carry = 0;
while (!list1.isEmpty() || !list2.isEmpty() || carry != 0) {
//为空返回0
int a = list1.isEmpty() ? 0 : list1.pop().val;
int b = list2.isEmpty() ? 0 : list2.pop().val;
int value = a + b + carry;
//获取进位
carry = value / 10;
//保证只有一位
value = value % 10;
//头插法插入结点
ListNode cur = new ListNode(value);
cur.next = newHead.next;
newHead.next = cur;
} return newHead.next;
}
}