面试题76:单链表的归并排序

来源:互联网 发布:多路访问网络 编辑:程序博客网 时间:2024/05/21 13:30

时间复杂度: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 Listthen 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;}


0 0
原创粉丝点击