leetcode_23_Merge k Sorted Lists

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢微笑


Merge k Sorted Lists 

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


//堆可以用来解决这个问题。
//C++的STL中priority_queue,优先队列就是堆结构。
//时间复杂度是O(NlogK),N是总数据个数,K是List的个数。


//堆可以用来解决这个问题。
//C++的STL中priority_queue,优先队列就是堆结构。
//时间复杂度是O(NlogK),N是总数据个数,K是List的个数。

 struct compare{
	bool operator()(ListNode *a , ListNode *b)
	{
		return a->val > b->val;
	}
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        priority_queue< ListNode * , vector<ListNode *> , compare> queue;
		for(int i=0; i<lists.size(); i++)
			if(lists[i] != NULL)
			{
				queue.push(lists[i]);
			}

		ListNode *head=NULL , *cur=NULL , *temp=NULL;
		while(!queue.empty())
		{
			temp = queue.top();
			queue.pop();
			if( cur==NULL )
				head = temp;
			else
				cur->next = temp;
			cur = temp;
			if(temp->next!=NULL)
				queue.push(temp->next);
		}
		return head;
    }
};



#include<iostream>
#include<vector>
#include<queue>

using namespace std;

#define N 5

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

struct compare{
	bool operator()(ListNode *a , ListNode *b)
	{
		return a->val > b->val;
	}
};

 struct compare{
	bool operator()(ListNode *a , ListNode *b)
	{
		return a->val > b->val;
	}
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        priority_queue< ListNode * , vector<ListNode *> , compare> queue;
		for(int i=0; i<lists.size(); i++)
			if(lists[i] != NULL)
			{
				queue.push(lists[i]);
			}

		ListNode *head=NULL , *cur=NULL , *temp=NULL;
		while(!queue.empty())
		{
			temp = queue.top();
			queue.pop();
			if( cur==NULL )
				head = temp;
			else
				cur->next = temp;
			cur = temp;
			if(temp->next!=NULL)
				queue.push(temp->next);
		}
		return head;
    }
};

ListNode *creatlist()
{
	ListNode *head = NULL;
	ListNode *p;
	for(int i=0; i<N; i++)
	{
		int a;
		cin>>a;
		p = (ListNode*) malloc(sizeof(ListNode));
		p->val = a;
		p->next = head;
		head = p;
	}
	return head;
}

int main()
{
	ListNode *list = creatlist();
	Solution lin;
	
	
}



你可能感兴趣的:(LeetCode,C++,stack,Linked_List)