23. Merge k Sorted Lists

来源:互联网 发布:nginx alias用法 编辑:程序博客网 时间:2024/05/20 22:39

1刷
思路是把每一个链表的首个val放入一个优先队列,然后每次pop就重新push同一个链表的点进入优先队列

主要是好多细节要注意:

重载
struct node
{
int val;
int num;
friend bool operator < (node n1, node n2){
return n1.val > n2.val;
}

};

2.ListNode *gg = new ListNode(t.val);

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    struct node    {        int val;        int num;        friend bool operator < (node n1, node n2){            return n1.val > n2.val;        }    };    ListNode* mergeKLists(vector<ListNode*>& lists) {        priority_queue<node>qu;        ListNode *g, *h;        for(int i = 0; i < lists.size(); ++ i){            if(lists[i] == NULL) continue;            node t;            t.val = lists[i] -> val;            t.num = i;            qu.push(t);            lists[i] = lists[i] -> next;        }        if(qu.empty()) return NULL;        else{            node t;            t = qu.top();            qu.pop();            ListNode *gg = new ListNode(t.val);            h = gg;g = gg;            if(lists[t.num] != NULL){                t.val = lists[t.num] -> val;                qu.push(t);                lists[t.num] = lists[t.num] -> next;            }        }        while(!qu.empty()){            node t;            t = qu.top();            qu.pop();            ListNode *gg = new ListNode(t.val);            g -> next = gg;            g = gg;            if(lists[t.num] != NULL){                t.val = lists[t.num] -> val;                qu.push(t);                lists[t.num] = lists[t.num] -> next;            }        }        g -> next = NULL;        return h;    }};

2刷
没想到2刷的思路跟一刷是一样的,都是用优先队列,但是2刷的代码写得好很多!

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    typedef struct node{        ListNode* t;        bool operator < (const node &b)const{            return t -> val > b.t -> val;        }    };    ListNode* mergeKLists(vector<ListNode*>& lists) {        priority_queue<node>qu;        for(int i = 0; i < lists.size(); ++ i){            node n;            if(lists[i] == NULL) continue;            n.t = lists[i];            lists[i] = lists[i] -> next;            qu.push(n);        }        ListNode* newhead = new ListNode(-1);        ListNode* tmp = newhead;        while(!qu.empty()){            node n = qu.top();            qu.pop();            tmp -> next = n.t;            tmp = tmp -> next;            n.t = n.t -> next;            if(n.t != NULL) qu.push(n);        }        tmp -> next = NULL;        return newhead -> next;    }};
0 0
原创粉丝点击