两数相加II
题目描述:
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。1
-
例如:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
-
题目解析:
- 链表存储的数据是从高位开始存储,在计算时需要进行处理(用栈存储元素,栈是先进后出).
- 结果输出也是从高位开始,用栈暂时先存储结果.
- 考虑计算时链表长度分为三部分:
- 当前位置链表均非null
- 当前位置有一个非null
- 当前位置另一个非null
- 处理进位
代码部分:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//借助栈求解
if(l1 == null && l2 != null) return l2;
if(l1 != null && l2 == null) return l1;
if(l1 == null && l2 == null) return null;
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
Stack<Integer> stack3 = new Stack<Integer>();
//数据入栈操作
ListNode temp1 = l1;
ListNode temp2 = l2;
while(temp1 != null){
stack1.push(temp1.val);
temp1 = temp1.next;
}
while(temp2 != null){
stack2.push(temp2.val);
temp2 = temp2.next;
}
//开始运算
int sol = 0;//进位
while((!stack1.isEmpty()) && (!stack2.isEmpty())){
int num1 = stack1.pop();
int num2 = stack2.pop();
int res = num1 + num2 + sol;
sol = res / 10;
stack3.push(res%10);
}
while(!stack1.isEmpty()){
int num1 = stack1.pop();
int res = num1 + sol;
sol = res / 10;
stack3.push(res%10);
}
while(!stack2.isEmpty()){
int num2 = stack2.pop();
int res = num2 + sol;
sol = res / 10;
stack3.push(res%10);
}
if(sol != 0) stack3.push(sol);
ListNode res = new ListNode(0);
ListNode temp3 = res;
while(!stack3.isEmpty()){
temp3.next = new ListNode(stack3.pop());
temp3 = temp3.next;
}
return res.next;
}
https://leetcode-cn.com/problems/add-two-numbers-ii/ ↩︎