题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

import java.util.*;
public class Solution {

    public ListNode addInList (ListNode head1, ListNode head2) {

        if (head1 == null && head2 == null) return null;
        if (head1 == null) return head2;
        if (head2 == null) return head1;

        // 先将链表反转
        head1 = rever(head1);
        head2 = rever(head2);

        ListNode c1 = head1;
        ListNode c2 = head2;
        // 新头节点
        ListNode phead = new ListNode(0);
        ListNode ret = phead;

        int carry = 0;//进位

        //进位也要不等于0
        while (c1 != null || c2 != null || carry != 0) {
            int val1 = c1 == null ? 0 : c1.val;
            int val2 = c2 == null ? 0 : c2.val;
            int t = val1 + val2 + carry;
            // 取进位
            carry = t / 10;
            int g = t % 10;
            ListNode tmp = new ListNode(g);
            phead.next = tmp;
            phead = phead.next;

            // 不为空时才能后移
            if(c1!=null)c1 = c1.next;
            if(c2!=null)c2 = c2.next;
        }

        // 此处不能用phead,phead已经移到最后了
        return rever(ret.next);
    }

    public ListNode rever(ListNode head){
        if(head ==null) return null;
        ListNode newHead = null;
        ListNode tmp = head;
        ListNode cur = head;

        while(cur!=null){
            tmp = cur.next;
            cur.next = newHead;
            newHead = cur;
            cur = tmp;
        }
        return newHead;
    }
}

全部评论

相关推荐

CARLJOSEPH...:宝宝你戾气太大了
点赞 评论 收藏
分享
来个大佬救一下,为上投了都是石沉大海了,没实习经历的话怕秋招直接进不了面。什么实习这么难找,基本
心态爆炸了:现在正式的岗位都少,实习基本不咋招的,除了大厂,中小企业其实没那么多岗位需求,就算是有,大多都是招一两个廉价劳动力,同时,他们也会希望你一来就能干活的,没时间培训你,就让你了解公司的项目,你了解完就可以开始干活。再者是,很多低质量的实习其实用处没有那么大的。我去年也是找实习找到破防,最后去了一家深圳的小公司实习,工作对我来说很简单,甚至不如我在学校做的项目,秋招的时候,这段实习经历也并没有帮上什么忙,投递简历,依旧非常低的回复率。低回复率是常态,尤其是找实习,找不到,那就把重心放在优化自己的简历和项目,多看八股文,锻炼自己的面试能力,多看别人的面经,自己模拟面试,等秋招的时候,只要有那么寥寥几次,好好抓住那几次机会。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务