面试题76:单链表的归并排序
2016-04-07 15:34
162 查看
时间复杂度:O(nlgn)
#include <iostream> #include <string> using namespace std; /* MergeSort(headRef) 1) If head is NULL or there is only one element in the Linked List then return. 2) Else divide the linked list into two halves. FrontBackSplit(head, &a, &b); // a and b are two halves 3) Sort the two halves a and b. MergeSort(a); MergeSort(b); 4) Merge the sorted a and b(using SortedMerge() discussed here) and update the head pointer using headRef. *headRef = SortedMerge(a, b); */ struct Node{ int val; Node *next; Node(int _val) :val(_val), next(NULL){} }; void FrontBackSplit(Node *head, Node **a, Node **b) { if (head == NULL || head->next == NULL) return; Node *faster = head->next; Node *slower = head; while (faster && faster->next) { slower = slower->next; faster = faster->next->next; } *b = slower->next; slower->next = NULL; *a = head; } Node *SortedMerge(Node *a, Node *b) { if (a == NULL) return b; if (b == NULL) return a; Node *head = NULL; if (a->val < b->val) { head = a; a = a->next; } else{ head = b; b = b->next; } Node *pNext = head; while (a && b) { if (a->val < b->val) { pNext->next = a; a = a->next; } else { pNext->next = b; b = b->next; } pNext = pNext->next; } if (a) pNext->next = a; else pNext->next = b; return head; } void MergeSort(Node **head) { if (!(*head) || !(*head)->next) return; Node *a = NULL, *b = NULL; FrontBackSplit(*head, &a, &b); MergeSort(&a); MergeSort(&b); *head = SortedMerge(a, b); } //main函数进行测试 int main() { Node *n1 = new Node(2); Node *n2 = new Node(1); Node *n3 = new Node(4); Node *n4 = new Node(3); Node *n5 = new Node(5); n1->next = n2; n2->next = n3; n3->next = n4; n4->next = n5; MergeSort(&n1); while (n1) { cout << n1->val << " "; n1 = n1->next; } cout << endl; return 0; }
相关文章推荐
- 【程序猿人生】关爱程序猿 从此刻开始!
- 面试题48 不能被继承的类
- 用户空间驱动
- 一个程序员的时间管理
- 经典面试题
- java工程师常见面试题
- java面试重点
- 从一生的角度看程序员的学习和发展
- 如何写出让hr一看就约你面试的简历
- 码农小汪-ajax详解
- iOS程序员必读之热门书单
- 【笔试/面试】—— 有向无环图(DAG)的最短路径问题(动态规划)
- LeetCode(30)-Pascal's Triangle
- 面试题44 扑克牌顺子
- 各类程序员学习路线图
- 面试题75:八皇后问题
- 鸡汤君_一个老程序员的建议66
- 招一个靠谱的iOS程序员 - 轩哥整理
- 面试题43 n个骰子的点数
- 【Git配置技巧】01. 配置文件git config介绍 --[码农老毕的学习笔记]