链表的归并排序

我们对链表进行排序,使用归并排序来进行排序,时间复杂度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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值