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

链表相加(二)

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;
    }
}

全部评论

相关推荐

起名字真难233:人家只有找猴子的预算,来个齐天大圣他们驾驭不住呀😂😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
# 听劝,这个简历怎么改 #
14081次浏览 182人参与
# 面试被问“你的缺点是什么?”怎么答 #
6359次浏览 98人参与
# 水滴春招 #
16328次浏览 346人参与
# 入职第四天,心情怎么样 #
11280次浏览 63人参与
# 租房找室友 #
8005次浏览 53人参与
# 读研or工作,哪个性价比更高? #
26151次浏览 356人参与
# 职场新人生存指南 #
199185次浏览 5509人参与
# 参加完秋招的机械人,还参加春招吗? #
26977次浏览 276人参与
# 文科生还参加今年的春招吗 #
4108次浏览 31人参与
# 简历无回复,你会继续海投还是优化再投? #
48619次浏览 561人参与
# 你见过最离谱的招聘要求是什么? #
144719次浏览 829人参与
# 如果重来一次你还会读研吗 #
155714次浏览 1706人参与
# 机械人选offer,最看重什么? #
69076次浏览 449人参与
# 选择和努力,哪个更重要? #
44269次浏览 492人参与
# 如果再来一次,你还会学硬件吗 #
103643次浏览 1245人参与
# 如果你有一天可以担任公司的CEO,你会做哪三件事? #
20519次浏览 413人参与
# 招聘要求与实际实习内容不符怎么办 #
46703次浏览 494人参与
# 22届毕业,是读研还是拿外包offer先苟着 #
4652次浏览 27人参与
# 你们的毕业论文什么进度了 #
901211次浏览 8960人参与
# 软开人,你觉得应届生多少薪资才算合理? #
81371次浏览 496人参与
# 国企还是互联网,你怎么选? #
109189次浏览 853人参与
牛客网
牛客企业服务