标签:merge k sorted lists leetcode 链表 merge
Merge k Sorted Lists
/** * 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; } };
leetcode 之 Merge k Sorted Lists
标签:merge k sorted lists leetcode 链表 merge
原文地址:http://blog.csdn.net/fangjian1204/article/details/39120051