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

链表相加(二)

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
        int a = 0, b = 0;
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        ListNode virtualHead1 = new ListNode(0);
        virtualHead1.next = head1;
        ListNode prev = virtualHead1;
        ListNode cur = head1;
        ListNode next = head1.next;
        ListNode newHead1 = head1, newHead2 = head2;

        while (head1.next != null) {
            ListNode t = head1.next;
            head1.next = head1.next.next;
            t.next = newHead1;
            newHead1 = t;
        }
        while (head2.next != null) {
            ListNode t = head2.next;
            head2.next = head2.next.next;
            t.next = newHead2;
            newHead2 = t;
        }
        ListNode heading = new ListNode(0);
        int nextIncr = 0;
        while (newHead1 != null || newHead2 != null) {
            int val = (newHead1 == null ? 0 : newHead1.val) + (newHead2 == null ? 0 :
                      newHead2.val) + nextIncr;
            int remaining = val % 10;
            nextIncr = val / 10;

            ListNode t = new ListNode(remaining);
            t.next = heading.next;
            heading.next = t;

            newHead1 = newHead1 == null ? null : newHead1.next;
            newHead2 = newHead2 == null ? null : newHead2.next;
        }
        if (nextIncr > 0) {
            ListNode t = new ListNode(nextIncr);
            t.next = heading.next;
            heading.next = t;
        }

        return heading.next;

    }
}

全部评论

相关推荐

uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
白火同学:只是实习的话,你这份简历应该也差不多了。真要优化的话,因为面实习的话,没有开发经验,面试更重视技术栈水平。 1、重视JavaSE的基础吧,集合、泛型算是比较基础的基础,多线程、反射、JVM内存模型才是基础; 2、技术栈写到具体的点,比如Elasticsearch的使用写到某个点,限制面试官自由发挥,防止问了相关问题最后又答不上,如果真没把握建议不写,降低面试官的心理预期; 3、技术栈不要重复,比如技术栈第二条和第八条可以合并改为“熟悉Redis中间件,包括基本数据结构、缓存策略、持久化机制,了解缓存三剑客及其解决方案,并有相关项目经验。”; 4、项目指标量化,比如“达到xx秒的响应速度”(不过这个就有点偏校招社招的要求了,实习简历不写也无伤大雅)。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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