题目
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
难点
本题的主要难点在于链表中数位的顺序与我们做加法的顺序是相反的,为了逆序处理所有数位,我们可以使用栈:把所有数字压入栈中,再依次取出相加。
最后使用头插法记录每一位的val,返回此链表
头插法的主要步骤:
- 给要插入的节点赋值
ListNode curNode = new ListNode(cur);
- 将要插入的节点的指针域指向 即将要插入的链表的头节点(ans)
curNode.next = ans;
- 更新头节点,插入之后的头节点为新插入的这个节点
ans = curNode;
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//2个链表2个栈
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
while(l1 != null){
stack1.push(l1.val);
l1 = l1.next;
}
while(l2 != null){
stack2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
//ListNode dummy = new ListNode(0);
ListNode ans = null;
//dummy.next = ans;
while(!stack1.isEmpty() || !stack2.isEmpty() || carry > 0){
int a = stack1.isEmpty() ? 0 : stack1.pop();
int b = stack2.isEmpty() ? 0 : stack2.pop();
int cur = a + b + carry;
carry = cur/10;//取整
cur %= 10;//取余
ListNode curNode = new ListNode(cur);
curNode.next = ans;
//dummy.next = curNode;
ans = curNode;
}
return ans;
}
}