• 21 合并两个有序链表(LeetCode HOT 100)


    描述:
    将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

    示例 1:

    输入:l1 = [1,2,4], l2 = [1,3,4]
    输出:[1,1,2,3,4,4]
    

    示例 2:

    输入:l1 = [], l2 = []
    输出:[]
    

    示例 3:

    输入:l1 = [], l2 = [0]
    输出:[0]
    

    提示:
    两个链表的节点数目范围是 [0, 50]
    -100 <= Node.val <= 100
    l1 和 l2 均按 非递减顺序 排列

    Soulution:

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            ListNode sentry = new ListNode(-999);
            ListNode point = sentry;
            while (list1 != null && list2 != null) {
                if (list1.val < list2.val) {
                    point.next = list1;
                    list1 = list1.next;
                } else {
                    point.next = list2;
                    list2 = list2.next;
                }
                point = point.next;
            }
            if (list1 == null) {
                point.next = list2;
            } else {
                point.next = list1;
            }
            return sentry.next;
        }
    

    Idea:
    简单的链表合并。这个归并思路,也用在了归并排序。

    Reslut:

  • 相关阅读:
    Single Number II
    Best Time to Buy and Sell Stock
    Linked List Cycle
    Single Number
    Max Points on a Line
    Strategy
    LRU Cache
    Word Break II
    Text Justification
    Median of Two Sorted Arrays
  • 原文地址:https://www.cnblogs.com/supermingjun/p/16125800.html
Copyright © 2020-2023  润新知