445. Add Two Numbers II 不会写理解了答案

本文介绍了一种解决两个非空链表表示的非负整数相加的方法。通过将链表值压入栈中,逐位相加并处理进位,最终构建出结果链表。
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
        //push all value into stack
        while(l1!=null){
            s1.push(l1.val);
            l1=l1.next;
        }
        while(l2!=null){
            s2.push(l2.val);
            l2=l2.next;
        }
        //get the value out one by one while doing add
        int sum=0;
        ListNode cur = new ListNode(0);
        while(!s1.empty()||!s2.empty()){
            if(!s1.empty()) sum+=s1.pop();
            if(!s2.empty()) sum+=s2.pop();
            cur.val = sum%10;
            ListNode head = new ListNode(sum/10);//括号里是val 参看ListNode的定义
            head.next = cur;
            cur = head;//this means that the first getin is the last node in the list
            sum/=10;
        }
        return cur.val==0?cur.next:cur;//judge whether the cur.val ==0 or not. if == 0, then the first node need to be the cur.next. if not, the first node is cur
    }
}

补充题目:

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

LinkedList 还有一些常用的函数:

size(): return the number of element in the list

add(e): add element


这里 list就是代码里的cur

每次循环,上一次循环虽然list被赋值了,但是新的循环会update它的值


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值