合并k个排序链表-LintCode

来源:互联网 发布:g92内螺纹编程实例 编辑:程序博客网 时间:2024/05/29 05:55

合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。
样例:
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null
.h

#ifndef C104_H#define C104_H#include<iostream>#include<vector>using namespace std;class ListNode{public:    int val;    ListNode *next;    ListNode(int val){        this->val = val;        this->next = NULL;    }};class Solution {public:    /**    * @param lists: a list of ListNode    * @return: The head of one sorted list.    */    ListNode *mergeKLists(vector<ListNode *> &lists) {        // write your code here        int len = lists.size();        for (int i = 0; i < len - 1; ++i)        {            lists[i + 1] = merge(lists[i], lists[i + 1]);        }        return lists[len - 1];    }    ListNode *merge(ListNode *head1, ListNode *head2)    {        ListNode *p = head1, *q = head2;        ListNode *node = new ListNode(0);        ListNode *pn = node;        while (p != NULL||q != NULL)        {                       if (p != NULL&&q != NULL)            {                if (p->val <= q->val)                {                    pn->next = p;                    pn = pn->next;                    p = p->next;                }                else                {                    pn->next = q;                    pn = pn->next;                    q = q->next;                }            }            else if (p != NULL&&q == NULL)            {                pn->next = p;                pn = pn->next;                p = p->next;            }            else            {                pn->next = q;                pn = pn->next;                q = q->next;            }        }        return node->next;    }};#endif

.cpp

#include"c104.h"int main(){    ListNode *p1 = new ListNode(2);    p1->next = new ListNode(4);    ListNode *p2 = new ListNode(3);    p2->next = new ListNode(5);    ListNode *p3 = new ListNode(6);    p3->next = new ListNode(7);    ListNode *p4 = new ListNode(1);    p4->next = new ListNode(10);    vector<ListNode*> v;    v.push_back(p1);    v.push_back(p2);    v.push_back(p3);    v.push_back(p4);    Solution s;    ListNode *p = s.mergeKLists(v);    while (p != NULL)    {        cout << p->val << " ";        p = p->next;    }    cout << endl;    return 0;}
原创粉丝点击