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

链表相加(二)

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        // 解题思路:
        // 1.如果head1 为null,则返回head2,反之也是。
        // 2.对head1 和 head2 进行链表反转
        // 3.循环遍历  head1 不为null或head2 不为null,则取他们的值相加
        // 对10取余作为新节点的值,对10取整作为下一次计算的初始值
        // 向后移动链表
        // 跳出循环后,需要注意初始值是否大于0
        // 最后对新链表反转
        if (head1 == null) {
            return head2;
        }

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

        ListNode r1 = reverse( head1);
        ListNode r2 = reverse( head2);
        int temp = 0;

        ListNode root = new ListNode(-1);
        ListNode cur = root;

        while (r1 != null || r2 != null) {
            int v1 = (r1 == null) ? 0 : r1.val;
            int v2 = (r2 == null) ? 0 : r2.val;

            int sum = temp + v1 + v2;
            temp = sum / 10;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;

            if (r1 != null) {
                r1 = r1.next;
            }

            if (r2 != null) {
                r2 = r2.next;
            }

        }

        if (temp > 0) {
            cur.next = new ListNode(temp);
        }

        return reverse(root.next);
    }

    private ListNode reverse(ListNode head1) {
        if (head1 == null) {
            return null;
        }

        ListNode pre = null;
        ListNode next;

        while (head1 != null) {
            next = head1.next;
            head1.next = pre;
            pre = head1;
            head1 = next;
        }

        return pre;
    }
}

全部评论

相关推荐

05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
点赞 评论 收藏
分享
04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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