现在的位置: 首页 > 综合 > 正文

leetcode 之 Merge k Sorted Lists

2017年01月30日 ⁄ 综合 ⁄ 共 967字 ⁄ 字号 评论关闭

Merge k Sorted Lists


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

思路:把这k个链表放入multiset中,每次从multiset中取出头结点最小的链表,把头结点插入到结果链表中,然后把剩下的非空子链表插入到multiset中
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    struct cmp//注意比较函数的格式,set的比较函数要么重载operator<,要么写成函数调用的形式
    {
    	bool operator()( ListNode* const l1, ListNode* const l2)const //注意参数的形式
    	{
    		if(!l1)return false;
    		if(!l2)return true;
            return l1->val<l2->val; 
    	}
    };
    
    ListNode *mergeKLists(vector<ListNode *> &lists)
    {
    	int length = lists.size(),i;
    	if(length <= 0)return NULL;
    	multiset<ListNode*,cmp> s;//相同的元素也要插入
    	for (i = 0;i < length;i++)
    	{
	    	if(lists[i])s.insert(lists[i]);//取出NULL链表
	    }
    	ListNode* head = NULL,*tail = NULL;
    	while (!s.empty())
    	{
    		multiset<ListNode*,cmp>::iterator iter = s.begin();
		    ListNode* p = *iter;
	    	s.erase(iter);//不能删除p,因为这样会删除所有头结点和p相同的链表
    		if(!head)
    		{
    			head = p;
    			tail = head;
    		}
    		else 
    		{
    			tail -> next = p;
    			tail = p;
    		}
    		p = p->next;
    		if(p)s.insert(p);
    	}
    	if(head)tail ->next = NULL;
    	return head;
    }
};

 

抱歉!评论已关闭.