您的位置:首页 > 其它

leetcode 27: Merge k Sorted Lists

2013-01-11 04:38 253 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

keypoints: 1 be familiar with use of pointer to pointer ** pre, no need for a dummy head node.

2. when the container need erase or insert, it's probably a sign of using list instead of vector.

3. when use erase or insert function in vector and list, the argument must be iterator not index. Whereas, the argument is index position in string class.

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//if( lists.size() <= 1) return intervals;
list<ListNode* > mylist;

for( int i=0; i< lists.size(); i++){
if(lists[i] != NULL) {
mylist.push_back( lists[i] );
}
}

ListNode * head = NULL;
ListNode ** pre = &head;

while( ! mylist.empty()) {
list<ListNode* > :: iterator minIt = mylist.begin();
list<ListNode* > :: iterator it = mylist.begin();

while( ++it != mylist.end() ) {
if( (*it)->val < (*minIt)->val ) {
minIt = it;
}
}

*pre = *minIt;
if( (*minIt)->next == NULL ) {
mylist.erase( minIt );
} else {
(*minIt) = (*minIt)->next ;
}
pre = &( (*pre)->next);
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: