题目描述
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码实现
package com.leetcode.链表;
import java.util.Stack;
/**
* Author:markusZhang
* VM Args:
* Date:Create in 2020/2/2 15:00
*/
public class 两数相加II {
static class ListNode{
int val;
ListNode next;
public ListNode(){}
public ListNode(int val){
this.val = val;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
Stack<Integer> stack1 = new Stack<>();//用于使l1入栈
Stack<Integer> stack2 = new Stack<>();//用于使l2入栈
Stack<Integer> stack3 = new Stack<>();//用于使结果入栈;
while(l1!=null){
stack1.push(l1.val);
l1 = l1.next;
}
while(l2!=null){
stack2.push(l2.val);
l2 = l2.next;
}
boolean isCarry = false; //判断是否进位
while(!stack1.isEmpty() || !stack2.isEmpty()){
int sum = 0;
if(!stack1.isEmpty()){
sum = sum+stack1.pop();
}
if(!stack2.isEmpty()){
sum = sum+stack2.pop();
}
if(isCarry){
sum++;
}
stack3.push(sum%10);
isCarry = sum>=10?true:false;
}
if(isCarry){
stack3.push(1);
}
ListNode newNode = new ListNode(-1);
ListNode pNode = newNode;
while(!stack3.isEmpty()){
pNode.next = new ListNode(stack3.pop());
pNode = pNode.next;
}
return newNode.next;
}
}