一、题目描述
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例 1:
输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]
示例 2:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[8,0,7]
示例 3:
输入:l1 = [0], l2 = [0]
输出:[0]
二、解题
栈
使用栈的思想,将数据进栈,然后出栈与进位相加,保存至节点中
/**
* 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) {
//典型的栈操作
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 node = null;
//当栈1不为空或者栈2不为空或者最后的进位不为0时
while(!stack1.isEmpty() || !stack2.isEmpty() || carry != 0){
int s1 = stack1.isEmpty()?0:stack1.pop();
int s2 = stack2.isEmpty()?0:stack2.pop();
int sum = s1+s2+carry;
carry = sum/10;
sum %= 10;
ListNode cur = new ListNode(sum);
cur.next = node;
node = cur;
}
return node;
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//栈
Deque<Integer> stack1 = new LinkedList<Integer>();
Deque<Integer> stack2 = new LinkedList<>();
while(l1 != null){
stack1.push(l1.val);
l1 = l1.next;
}
while(l2 != null){
stack2.push(l2.val);
l2 = l2.next;
}
ListNode dummy = new ListNode(-1);
ListNode node = new ListNode(-1);
dummy.next = node;
//出栈
int carry = 0;
while(carry == 1 || !stack1.isEmpty() || !stack2.isEmpty()){
int x = stack1.isEmpty() ? 0 : stack1.pop();
int y = stack2.isEmpty() ? 0 : stack2.pop();
int sum = x+y+carry;
carry = sum / 10;
sum = sum % 10;
ListNode cur = new ListNode(sum);
node.next = cur;
node = cur;
}
return reverse(dummy.next.next);
}
public ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode cur = reverse(head.next);
head.next.next = head;
head.next = null;
return cur;
}
}