• 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)

     
  • 相关阅读:
    CF 986A Fair——多源bfs
    poj3539 Elevator——同余类bfs
    poj3463 Sightseeing——次短路计数
    poj2262 Goldbach's Conjecture——筛素数
    Kruskal算法
    Prim算法
    离散化
    最短路(hdu2544)
    最短路径问题
    Servlet
  • 原文地址:https://www.cnblogs.com/s-c-x/p/10043412.html
Copyright © 2020-2023  润新知