题目:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路:
本题使用栈来解决,先将两数组数字输入栈,此时注意栈大小要相等,不相等则加0。再讲两栈对应元素相加,将和输入新的栈,此时顺序即为反序,但此时有元素大于10,还需进行进位操作。建立一个数组存储进位后的元素,再返回最终链表。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
{
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
Stack<Integer> stack3 = new Stack<>();
//l1入栈
while (l1!=null)
{
stack1.add(l1.val);
l1=l1.next;
}
//l2入栈
while (l2!=null)
{
stack2.add(l2.val);
l2=l2.next;
}
//比较两栈大小,往少的那个添加0
while (stack1.size()!=stack2.size())
{
if (stack1.size()<stack2.size())
stack1.add(0);
else stack2.add(0);
}
//将两栈对应数相加,再入新栈
while (!stack1.isEmpty()) {
stack3.add(stack1.pop() + stack2.pop());
}
//建立数组,存放所有位数上的数字,建立进位carry
ArrayList<Integer> arr = new ArrayList<>();
int carry=0;
while (!stack3.isEmpty()||carry!=0){
int current =0;
if (!stack3.isEmpty())
current = stack3.pop()+carry;
else
current=carry;
carry=0;
if (current>=10)
{
current=current-10;
carry=1;
}
arr.add(current);
}
ListNode l3 = new ListNode(arr.get(0));
ListNode l4 = l3;
if (arr.size()==1)
return l3;
else {
for (int i = 1; i < arr.size(); i++) {
l3.next = new ListNode(arr.get(i));
l3=l3.next;
}
}
return l4;
}
}
}