zoukankan      html  css  js  c++  java
  • leetcode21- Merge Two Sorted Lists- easy

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

    问清楚需不需要创造新节点。算法比较简单,比较后接上即可,就是小心心里跑一下corner case,看[][], [][1], [1][] 这几个会不会有空指针问题。

    1. 创造新节点

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            
            ListNode dummy = new ListNode(-1);
            ListNode crt = dummy;
            while (l1 != null || l2 != null) {
                // 一定要写全条件了,这样写对l1为null但l2不为null的case走进去判断会报空指针!!
                // if (l2 == null || l1.val <= l2.val) {
                if (l1 == null) {
                    crt.next = new ListNode(l2.val);
                    crt = crt.next;
                    l2 = l2.next;
                } else if (l2 == null) {
                    crt.next = new ListNode(l1.val);
                    crt = crt.next;
                    l1 = l1.next;
                } else if (l1.val <= l2.val) {
                    crt.next = new ListNode(l1.val);
                    crt = crt.next;
                    l1 = l1.next;
                } else {
                    crt.next = new ListNode(l2.val);
                    crt = crt.next;
                    l2 = l2.next;
                }
            }
            return dummy.next;
        }
    }

    2.不创造新节点

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            
            ListNode dummy = new ListNode(-1);
            ListNode crt = dummy;
            while (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    crt.next = l1;
                    l1 = l1.next;
                } else {
                    crt.next = l2;
                    l2 = l2.next;
                }
                crt = crt.next;
            }
            
            if (l1 == null && l2 != null) {
                crt.next = l2;
            } else if (l1 != null && l2 == null) {
                crt.next = l1;
            }
            return dummy.next;
        }
    }
  • 相关阅读:
    百度Apollo安装说明
    Ubuntu 16.04 kinetic 下安装turtlebot2
    三维点云地图构建方法
    jupyter中添加conda环境
    Pyplot教程(深度学习入门3)
    linux下安装tomcat,部署项目
    linux下修改系统时间
    手把手集成web端手写公式功能
    如何查看端口是被哪个程序占用的
    Bootstrap的优先级、选择器、伪类
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7809057.html
Copyright © 2011-2022 走看看