版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/love905661433/article/details/84842369
题目
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
解题
- 将两个链表倒转之后,就转换成了2号问题, 代码如下:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = linkedListToStack(l1);
Stack<Integer> s2 = linkedListToStack(l2);
Stack<Integer> result = new Stack<>();
int num1, num2;
int sum = 0;
int carry = 0;
while ((!s1.isEmpty()) || (!s2.isEmpty())){
if (!s1.isEmpty()){
num1 = s1.pop();
} else {
num1 = 0;
}
if (!s2.isEmpty()){
num2 = s2.pop();
} else {
num2 = 0;
}
sum = num1 + num2 + carry;
carry = sum / 10;
result.push(sum % 10);
}
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
// 处理最后的进位
if (carry == 1) {
result.push(carry);
}
while (!result.isEmpty()) {
cur.next = new ListNode(result.pop());
cur = cur.next;
}
return dummyHead.next;
}
private Stack<Integer> linkedListToStack(ListNode head){
Stack<Integer> stack = new Stack();
while (head != null){
stack.push(head.val);
head = head.next;
}
return stack;
}
}