【算法题】链表归并排序
来源:互联网 发布:印度经济数据 编辑:程序博客网 时间:2024/06/15 10:05
链表的归并排序
#include <iostream>#include <vector>#include <numeric>#include <algorithm>using namespace std;struct ListNode{ ListNode* next; int value;};bool List_insert(ListNode ** phead, int x, int i){//空指针 if (phead == NULL) { return 0; } ListNode * pCurrent(NULL);//头插入 if (i==1) { pCurrent = *phead; ListNode * pNew = new ListNode; pNew->value = x; pNew->next = pCurrent; *phead = pNew; return 1; }//非头插入 pCurrent = *phead; ListNode * pfront(NULL); int k(1); while (k < i && pCurrent != NULL) { pfront = pCurrent; pCurrent = pCurrent->next; k++; } if (k != i) { return 0; } ListNode * pNew = new ListNode; pNew->value = x; pNew->next = pCurrent; pfront->next = pNew; return 1;}void List_print(ListNode * phead){ while (phead!=NULL) { cout << phead->value; phead = phead->next; } cout << endl;}ListNode* MergeSortList(ListNode * leftHead, ListNode * rightHead){ ListNode newhead, *tmp; newhead.next = leftHead->value >= rightHead->value ? leftHead : rightHead; tmp = &newhead; while (leftHead !=NULL && rightHead != NULL) { if (leftHead->value >= rightHead->value) { tmp->next = leftHead; tmp = tmp->next; leftHead = leftHead->next; } else { tmp->next = rightHead; tmp = tmp->next; rightHead = rightHead->next; } } if (leftHead != NULL) { tmp->next = leftHead; } if (rightHead != NULL) { tmp->next = rightHead; } return newhead.next;}ListNode * MergeSort(ListNode* phead){ if (phead == NULL||phead->next==NULL) { return phead; } ListNode * pslow(phead), *pfast(phead); while (pfast->next!=NULL&&pfast->next->next!=NULL) { pslow = pslow->next; pfast = pfast->next->next; } ListNode * leftHead = phead; ListNode * rightHead = pslow->next; pslow->next = NULL;//分割为两个链表 leftHead = MergeSort(leftHead); rightHead = MergeSort(rightHead); return MergeSortList(leftHead,rightHead);}int main(){ ListNode * phead = NULL; List_insert(&phead, 1, 1); List_insert(&phead, 2, 1); List_insert(&phead, 3, 1); ListNode * phead_2 = NULL; List_insert(&phead_2, 0, 1); List_insert(&phead_2, 4, 1); List_insert(&phead_2, 5, 1); List_print(phead); List_print(phead_2); phead = MergeSortList(phead, phead_2); List_print(phead); return 0;}
阅读全文
0 0
- 【算法题】链表归并排序
- 【算法题】归并排序
- 算法:链表的归并排序
- 高效链表排序-归并算法
- 链表的归并排序算法
- 排序算法-归并排序
- 排序算法------归并排序
- 排序算法-归并排序
- 排序算法---归并排序
- 排序算法--归并排序
- 排序算法--归并排序
- 排序算法-归并排序
- 排序算法--归并排序
- 排序算法--归并排序
- 排序算法:归并排序
- 排序算法-归并排序
- 排序算法:归并排序
- 【排序算法】归并排序
- 用友U8手工清除工作流资料
- UDOO X86比Raspberry Pi性能强10倍 Windows/Linux/Android通吃
- Java标识符的命名方法
- Template by 2015ljn
- Angular常见面试题
- 【算法题】链表归并排序
- 机器学习十大算法--SVM(支持向量机)
- 排序算法之快速排序<Quick_Sort>及其C语言代码实现
- Linux中的uniq命令(去掉重复项,输出重复项)
- 树的遍历关系深入理解(前序,中序,后序互求及分析)
- Neo4j 沙盒实验申请使用过程
- [运维]ESXI Web Client
- 桃花扇中的忠贞
- spring事务传播特性