您的位置:首页 > 其它

链表的归并排序

2014-10-24 22:18 274 查看
我们对链表进行排序,使用归并排序来进行排序,时间复杂度O(nlgn)。

此种方式的排序主要涉及到以下三个知识点:

1. 两个链表的归并;

2. 归并排序的思想;

3. 获取一个链表的中间结点;

我的归并排序代码如下,欢饮大家探讨!

#include <iostream>
#include <iomanip>
using namespace std;

class List;
class Node
{
private:
int data;
Node * next;
public:
Node()
{
this->next = NULL;
}
Node(int x):data(x),next(NULL)
{

}

friend class List;
};

class List
{
private:
Node* head;
public:
List()
{
head = new Node();
}
void Insert(int x)
{
Node* p = new Node(x);
p->next = head ->next ;
head->next = p;
}

Node* MergeList(Node* pLista, Node* pListb)
{
if(pLista == NULL)
return pListb;
if(pListb == NULL)
return pLista;
Node* pListc = new Node();
Node* pHead = pListc;
//pLista = pLista->next;
while(pLista && pListb)
{
if(pLista->data < pListb->data)
{
pListc->next = pLista;
pListc = pListc->next;
pLista = pLista->next;
}
else
{
pListc->next = pListb;
pListc = pListc->next;
pListb = pListb->next;
}
}
pListc->next = (pLista) ? pLista : pListb;
return pHead->next;
}

Node* GetMid(Node* pList)
{
if(pList == NULL)
return NULL;
if(pList->next == NULL)
return pList;
Node *p = pList;
pList = pList->next;
while(pList && pList->next)
{
p = p->next;
pList = pList->next->next;
}
return p;
}

Node* ListMergeSort(Node* pList)
{
if(pList == NULL)
return NULL;
if(pList->next == NULL)
return pList;
Node* pMid = this->GetMid(pList);
Node* pMidNext = NULL;
if(pMid)
{
pMidNext = pMid->next;
pMid->next = NULL;
}
Node* pLeft = ListMergeSort(pList);
Node* pRight = ListMergeSort(pMidNext);
return MergeList(pLeft,pRight);
}

void PrintList()
{
Node* p = this->head->next;
while(p)
{
cout<<setw(5)<<p->data;
p = p->next;
}
cout<<endl;
}

Node* GetHeadNext()
{
return this->head->next;
}

};

int main()
{
List L;
for(int i = 0 ; i < 12 ; i++)
L.Insert(rand()%65);
L.PrintList();
L.ListMergeSort(L.GetHeadNext());
L.PrintList();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表的归并排序