zoukankan      html  css  js  c++  java
  • C# 写 LeetCode easy #21 Merge Two Sorted Lists

    21、 Merge Two Sorted Lists

    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.

    Example:

    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4

    代码:
    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }
    
    static void Main(string[] args)
    {
        ListNode l11=new ListNode(1);
        ListNode l12 = new ListNode(3);
        ListNode l13 = new ListNode(4);
        l11.next = l12;
        l12.next = l13;
        ListNode l21 = new ListNode(2);
        ListNode l22 = new ListNode(3);
        ListNode l23 = new ListNode(5);
        l21.next = l22;
        l22.next = l23;
        var res=MergeTwoSortedLists(l11, l21);
        while (res != null)
        {
            Console.Write(res.val);
            res = res.next;
        }            
        Console.ReadKey();
    }
    
    private static ListNode MergeTwoSortedLists(ListNode l1, ListNode l2)
    {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        if (l1.val < l2.val)
        {
            l1.next = MergeTwoSortedLists(l1.next, l2);                
            return l1;
        }
        else
        {
            l2.next = MergeTwoSortedLists(l1, l2.next);
            return l2;
        }
    }

    解析

    输入:两个链表

    输出:合并后的链表

    思想

      三种情况分别讨论,并且用递归的思想。

    时间复杂度:O(n)

     
  • 相关阅读:
    图像处理-06-图像的反色处理
    Egg.js框架
    Node基础
    Node介绍与安装
    线性表结构-数组(散列表与可变长度数组)
    复杂度分析和大O表示法
    Java框架之Struts2(六)
    Java框架之Struts2(五)
    Java框架之Struts2(四)
    Java框架之Struts2(三)
  • 原文地址:https://www.cnblogs.com/s-c-x/p/10043412.html
Copyright © 2011-2022 走看看