1. 程式人生 > 實用技巧 >LeetCode_23.合併K個排序連結串列

LeetCode_23.合併K個排序連結串列

合併k個排序連結串列,返回合併後的排序連結串列。請分析和描述演算法的複雜度。

示例:

輸入:
[
 1->4->5,
 1->3->4,
 2->6
]
輸出: 1->1->2->3->4->4->5->6

C#程式碼

/**

  • Definition for singly-linked list.

  • public class ListNode {

  • public int val;
    
  • public ListNode next;
    
  • public ListNode(int x) { val = x; }
    
  • }
    */
    public class Solution {
    public ListNode MergeKLists(ListNode[] lists)
    {
    int index = 0;
    int count = lists.Length;
    int temp = 1;

     if (count == 0) return null;
    
     while (temp < count)
     {
         index = 0;
         while (index + temp < count)
         {
             lists[index] = MergeTwoList(lists[index], lists[index + temp]);
             index += temp * 2;
         }
         temp *= 2;
     }
     return lists[0];
    

    }

    public ListNode MergeTwoList(ListNode node1, ListNode node2)
    {
    Stack stack = new Stack();
    int val1, val2;
    while (node1 != null && node2 != null)
    {
    val1 = node1.val;
    val2 = node2.val;
    if (val1 <= val2)
    {
    stack.Push(val1);
    node1 = node1.next;
    }
    else
    {
    stack.Push(val2);
    node2 = node2.next;
    }
    }

     while (node1 != null)
     {
         val1 = node1.val;
         stack.Push(val1);
         node1 = node1.next;
     }
    
     while (node2 != null)
     {
         val2 = node2.val;
         stack.Push(val2);
         node2 = node2.next;
     }
    
     ListNode node = null;
     while (stack.Count > 0)
     {
         node = new ListNode() { val = stack.Pop(), next = node };
     }
     return node;
    

    }
    }