码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode长征系列】Merge k Sorted Lists

时间:2014-08-14 20:52:09      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:des   io   for   代码   amp   时间   size   ad   

原题:

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

思路:两条两条地合并。时间复杂度为O(n),n为所有链表节点和。

代码:

/**
 * 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) {
        if(lists.empty()) return NULL;
        if(lists.size()==1) return lists[0];
        
        ListNode *res;
        stack<ListNode*> now;
        int i = 0;
        ListNode *tmp1, *tmp2;
        
        now.push(lists[0]);
        now.push(lists[1]);
        i+=2;
        while(i<lists.size()){
            tmp1 = now.top();
            now.pop();
            tmp2 = now.top();
            now.pop();
            res = mergeTwo(tmp1,tmp2);
            if(i>=lists.size()) break;
            now.push(res);
            now.push(lists[i]);
            i++;
        }
        return res;
    }
    
    ListNode *mergeTwo(ListNode* former, ListNode* later){
        if(former==NULL && later!=NULL) return later;
        if(later==NULL && former!=NULL) return former;
        if(former==NULL && later==NULL) return NULL;
        
        ListNode *tmp = former, *tmp2 = later, *res, *head = NULL;
        
        if(tmp->val <= tmp2->val) {
            head = tmp;
            tmp = tmp->next;
        }
        else {
            head = tmp2;
            tmp2 = tmp2->next;
        }
        res = head;
        while(tmp && tmp2){
            if(tmp->val>tmp2->val) {
                res->next = tmp2;
                tmp2 = tmp2->next;
            }
            else {
                res->next = tmp;
                tmp = tmp->next;
            }
            res =res->next;
        }
        if(tmp!=NULL) res->next = tmp;
        if(tmp2!=NULL) res->next = tmp2;
        return head;
    }
};

但是RE了…

【Leetcode长征系列】Merge k Sorted Lists,布布扣,bubuko.com

【Leetcode长征系列】Merge k Sorted Lists

标签:des   io   for   代码   amp   时间   size   ad   

原文地址:http://blog.csdn.net/u010239096/article/details/38560739

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!