leetcode 27: Merge k Sorted Lists


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;
    }
};


posted @ 2013-01-11 04:38  西施豆腐渣  阅读(144)  评论(0编辑  收藏  举报