题目
给定两个 非空链表 l1和 l2 来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例
输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[8,0,7]
输入:l1 = [0], l2 = [0]
输出:[0]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lMSNwu
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:反转链表
Java实现
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode h1 = reverse(l1);
ListNode h2 = reverse(l2);
ListNode dummy = new ListNode();
ListNode pre = dummy;
int add = 0;
while (add != 0 || h1 != null || h2 != null) {
int a = h1 != null ? h1.val : 0;
int b = h2 != null ? h2.val : 0;
int var = a + b + add;
pre.next = new ListNode(var % 10);
pre = pre.next;
add = var / 10;
if (h1 != null) h1 = h1.next;
if (h2 != null) h2 = h2.next;
}
return reverse(dummy.next);
}
public ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
方法2:栈
本来打算用long型来做,这样就不用反转链表,不过没想到链表太长了直接long型溢出了。
看了题解发现像这种逆序的题要优先想到栈。
后面生成链表的时候,要用前插法。
Java实现
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
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;
}
ListNode pre = null;
int add = 0;
while (!stack1.isEmpty() || !stack2.isEmpty() || add != 0) {
int a = stack1.isEmpty() ? 0 : stack1.pop();
int b = stack2.isEmpty() ? 0 : stack2.pop();
int var = a + b + add;
ListNode tmp = new ListNode(var % 10);
tmp.next = pre;
pre = tmp;
add = var / 10;
}
return pre;
}
}