题目
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 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) {
Stack<Integer> s1 = new Stack();
Stack<Integer> s2 = new Stack();
while(l1!=null){
s1.push(l1.val);
l1 = l1.next;
}
while(l2!=null){
s2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
Integer sum = 0;
ListNode head = new ListNode(-1);
ListNode current = null;
while(!s1.isEmpty()||!s2.isEmpty()){
ListNode node = new ListNode(-1);
if(s1.isEmpty()){
sum = s2.pop()+carry;
node.val = sum%10;
carry = sum/10;
}else if(s2.isEmpty()){
sum = s1.pop()+carry;
node.val = sum%10;
carry = sum/10;
}else{
sum = s1.pop()+s2.pop()+carry;
node.val = sum%10;
carry = sum/10;
}
node.next = current;
current = node;
head.next = current;
}
if(carry>0){
ListNode node = new ListNode(carry);
node.next = current;
head.next = node;
}
return head.next;
}
}