题解 | #两个链表生成相加链表#

两个链表生成相加链表

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

1.首先把两个链表都反转
2.从头开始两个链表相加
3.反转相加后的链表

    public ListNode addInList2(ListNode head1, ListNode head2) {

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

        ListNode pre1 = null;
        ListNode next1;
        while (head1 != null) {
            next1 = head1.next;
            head1.next = pre1;
            pre1 = head1;
            head1 = next1;
        }

        ListNode pre2 = null;
        ListNode next2;
        while (head2 != null) {
            next2 = head2.next;
            head2.next = pre2;
            pre2 = head2;
            head2 = next2;
        }

        ListNode newHead = new ListNode(0);
        ListNode newTemp = newHead;

        int c = 0;
        while (pre1 != null || pre2 != null) {
            int a = 0;
            int b = 0;
            if (pre1 != null) {
                a = pre1.val;
                pre1 = pre1.next;
            }
            if (pre2 != null) {
                b = pre2.val;
                pre2 = pre2.next;
            }
            newTemp.next = new ListNode((a + b + c) % 10);
            newTemp = newTemp.next;
            c = (a + b + c) / 10;

        }

        if (c != 0) {
            newTemp.next = new ListNode(c);
        }
        ListNode head = newHead.next;
        ListNode pre = null;
        ListNode next = null;
        while (head != null) {

            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;

    }
全部评论

相关推荐

今天 13:04
已编辑
门头沟学院 算法工程师
智谱和米哈游都是ai大模型agent的业务钱的话还是米更多,几乎翻倍了,有没有老哥是两个公司其中一个的,能问问转正率咋样嘛,我问的hr回答都是做的好就可以转正暑期实习
码农索隆:选米哈游:短期高薪、敢承担风险、具备强创新能力,且愿押注游戏AI赛道。 选智谱:稳定性与行业通用能力积累,接受薪资差距以换取更稳妥的职业基础。
投递米哈游等公司6个岗位 > 实习期间如何提升留用概率?
点赞 评论 收藏
分享
Ncsbbss:又想干活又想要工资,怎么什么好事都让你占了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务