两数相加--LeetCode

题目:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 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;
    }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值