C# 寫 LeetCode easy #21 Merge Two Sorted Lists

2一、 Merge Two Sorted Listsnode

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.spa

Example:code

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;
    }
}

 

解析blog

輸入:兩個鏈表遞歸

輸出:合併後的鏈表ci

思想get

  三種狀況分別討論,而且用遞歸的思想。string

時間複雜度:O(n)it

相關文章
相關標籤/搜索