1、445题,
题目描述:给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
思路:
1、两数相加,要考虑到进位;
2、由于此题高位在链表头部,低位在链表尾部。而进位要考虑从低位开始。所以需要从尾部开始相加。所以,使用双栈法,从链表头部开始入栈,栈顶即为尾部的节点,进行相加操作。
代码:
import java.util.Stack;
public class T_445 {
private class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 定义两个栈
Stack <Integer> st1 = new Stack<Integer>();
Stack <Integer> st2 = new Stack<Integer>();
// 将链表各节点的val值入栈
while (l1 != null) {
st1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
st2.push(l2.val);
l2 = l2.next;
}
ListNode res = new ListNode(0);
// 进位变量
int carry = 0;
while (!st1.isEmpty() || !st2.isEmpty()) {
// 栈为空,补为0, 不为空,则弹出栈顶元素。
int n1 = st1.isEmpty() ? 0 : st1.pop();
int n2 = st2.isEmpty() ? 0 : st2.pop();
int sum = n1 + n2 + carry;
carry = sum / 10;
// 新节点前插入结果链表
ListNode cur = new ListNode(sum % 10);
cur.next = res.next;
res.next = cur;
}
// 判断最高位相加后是否有进位,若有,则新增一个节点。
if (carry != 0) {
ListNode cur = new ListNode(1);
cur.next = res.next;
res.next = cur;
}
return res.next;
}
}