[leetcode]merge-k-sorted-lists

题目描述

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

解法

  • 合并k个有序链表的解法与合并两个有序链表的解法类似
  • 先构造一个dummy结点,并把dummy赋值给cur,在循环中选择k个链表中值最小的头结点,使得cur的next指向最小的头结点,并使最小头结点所在链表的头结点往后移
  • 循环一直到k个链表都为空才结束
  • 代码实现
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode*>& lists) {
        ListNode* dummy = new ListNode(-1);
        ListNode* cur = dummy;
        
        int stop = false;
        while(!stop) {
            stop = true;
            int minIndex = -1;
            int minNum = INT_MAX;
            for(int i = 0; i < lists.size(); ++i) {
                if(lists[i] != nullptr) // 只要有一个链表不为空,就不退出循环
                    stop = false;
                if(lists[i] != nullptr && lists[i] -> val < minNum) { // 找到值最小的链表头结点
                    minNum = lists[i] -> val;
                    minIndex = i;
                }
            }
            
            if(minIndex >= 0) { // 改变cur -> next,以及调整最小头结点所在链表
                cur -> next = lists[minIndex];
                cur = cur -> next;
                lists[minIndex] = lists[minIndex] -> next;
            }
        }
        
        ListNode* res = dummy -> next;
        delete dummy;
        return res;
    }
};

你可能感兴趣的:(数据结构与算法)