leetcode21- Merge Two Sorted Lists- easy

断了今生、忘了曾经 提交于 2020-01-22 11:23:11

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);//注意这个一直创建new
                crt = crt.next;//自己指向自己的next 不创建新的  就是指向l2 l2仍是指向它自己
                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;//就不用再next什么了 直接l2 只有他了
        } else if (l1 != null && l2 == null) {
            crt.next = l1;
        }
        return dummy.next;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!