链表的归并排序
2014-10-24 22:18
274 查看
我们对链表进行排序,使用归并排序来进行排序,时间复杂度O(nlgn)。
此种方式的排序主要涉及到以下三个知识点:
1. 两个链表的归并;
2. 归并排序的思想;
3. 获取一个链表的中间结点;
我的归并排序代码如下,欢饮大家探讨!
此种方式的排序主要涉及到以下三个知识点:
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; }
相关文章推荐
- 链表排序--归并排序
- 链表排序(冒泡、选择、插入、快排、归并、希尔、堆排序)【转载】
- 将两个已排序的链表归并成一个链表(C++面试题)
- 单链表排序(插入与归并)
- 【面经笔记】链表归并排序
- C语言中数据结构之链表归并排序实例代码
- 链表排序(归并法)
- 链表排序(冒泡、选择、插入、快排、归并)
- C/C++ 数组,链表排序(平均时间复杂度 O(nlogn))归并、快速、堆、希尔之归并排序
- 单链表排序----快排 & 归并排序
- 归并排序之数组和链表
- 链表的各种操作实现 链表逆序 链表排序 有序链表归并 链表存在环的判定
- 链表排序(冒泡、选择、插入、快排、归并、希尔、堆排序)
- 单链表排序--归并排序
- Merge Two Sorted Lists 归并已排序的链表
- 链表的归并排序与快速排序
- 归并排序--数组和链表的实现
- 数据结构 29 排序 自己实现 插入排序 插入和归并综合排序 给链表排序
- 【每日算法】归并排序及其应用(逆序对&合并有序链表)
- 数据结构之排序大集合(下)(选择、堆、基数、归并,链表排序)