码迷,mamicode.com
首页 > Windows程序 > 详细

C# 写 LeetCode easy #21 Merge Two Sorted Lists

时间:2018-11-30 13:44:57      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:turn   sorted   etc   var   思想   并且   span   ==   res   

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)

 

 

C# 写 LeetCode easy #21 Merge Two Sorted Lists

标签:turn   sorted   etc   var   思想   并且   span   ==   res   

原文地址:https://www.cnblogs.com/s-c-x/p/10043412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!