445. 两数相加 II
题目描述
原题
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
| 输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
|
题解
方法一
| /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//先翻转链表 然后两个链表相加
//再翻转结果链表
l1 = reverse(l1);
l2 = reverse(l2);
ListNode dummyNode = new ListNode();
ListNode curr = dummyNode;
int carry = 0;
while(l1 != null || l2 !=null){
int x = l1!=null ? l1.val:0;
int y = l2!=null ? l2.val:0;
int sum = x + y + carry;
carry = sum / 10;
curr.next = new ListNode(sum%10);
curr = curr.next;
if(l1!=null) l1 = l1.next;
if(l2!=null) l2 = l2.next;
}
if(carry>0){
curr.next = new ListNode(carry);
}
return reverse(dummyNode.next);
}
private ListNode reverse(ListNode node){
ListNode pre = null;
ListNode curr = node;
while(curr!=null){
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
}
|
方法二
| /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
LinkedList<ListNode> stack1 = addToStack(l1);
LinkedList<ListNode> stack2 = addToStack(l2);
LinkedList<ListNode> stack3 = new LinkedList<>();
int carry = 0;
while(!stack1.isEmpty() || !stack2.isEmpty()||carry > 0){
int x = !stack1.isEmpty() ? stack1.pop().val:0;
int y = !stack2.isEmpty() ? stack2.pop().val:0;
int sum = x + y + carry;
carry = sum / 10;
stack3.push(new ListNode(sum % 10));
}
ListNode dummyNode = new ListNode();
ListNode curr = dummyNode;
while(!stack3.isEmpty()){
curr.next = stack3.pop();
curr = curr.next;
}
return dummyNode.next;
}
private LinkedList<ListNode> addToStack(ListNode node){
LinkedList<ListNode> stack = new LinkedList<>();
while(node!=null){
stack.push(node);
node = node.next;
}
return stack;
}
}
|
| class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//栈里面可以直接存储值 不用存储ListNode
Deque<Integer> stack1 = new LinkedList<Integer>();
Deque<Integer> stack2 = new LinkedList<Integer>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode pre = null;
while (!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
int a = stack1.isEmpty() ? 0 : stack1.pop();
int b = stack2.isEmpty() ? 0 : stack2.pop();
int sum = a + b + carry;
carry = sum / 10;
sum %= 10;
//这里借助了链表翻转的思路
ListNode curr = new ListNode(sum);
curr.next = pre;
pre = curr;
}
return pre;
}
}
|