单链表的归并排序

来源:互联网 发布:哪的java技术培训好 编辑:程序博客网 时间:2024/05/21 01:57

题目:单链表的归并排序

思路:首先找到链表的中间节点,将原始链表一分为二,递归进行该操作,直到被划分的两个链表包含的节点少于等于1个,即该次划分后两个链表已经有序。然后依次合并两个有序的链表,直到所有划分都合并完,即排序完毕。主要编写将两个有序链表合并为一个有序链表的函数。



#include<iostream>using namespace std;//链表结构struct ListNode{int key;ListNode* next;ListNode(int _key) :key(_key), next(NULL) {}};//将两个有序链表合并为一个有序链表ListNode* MergeList(ListNode* L1, ListNode* L2){if (L1 == NULL)return L2;if (L2 == NULL)return L1;ListNode* dummy = new ListNode(-1);//增加一个头结点便于算法中prv指针的操作ListNode* p1 = L1;ListNode* p2 = L2;ListNode* prv = NULL;//保存上一个节点if (p1->key > p2->key){dummy->next = p2;prv = dummy;}else{dummy->next = p1;prv = dummy;}while (p1 != NULL && p2 != NULL){while (p1!=NULL && p2!=NULL&& p1->key < p2->key){p1 = p1->next;prv = prv->next;}prv->next = p2;while (p2 != NULL && p1!=NULL && p2->key < p1->key){p2 = p2->next;prv = prv->next;}if(p1!=NULL)prv->next = p1;}ListNode* retHead =dummy->next;//要返回的第一个节点delete dummy;return retHead;}//归并主函数ListNode* ListMergeSort(ListNode* pHead){if (pHead == NULL || pHead->next == NULL)return pHead;ListNode* slow = pHead;ListNode* fast = pHead;while (fast->next != NULL && fast->next->next != NULL){fast = fast->next->next;slow = slow->next;}ListNode* leftHead  = pHead;ListNode* rightHead = slow->next;slow->next = NULL;ListMergeSort(leftHead);ListMergeSort(rightHead);return MergeList(leftHead, rightHead);}void showList(ListNode* pHead){while (pHead != NULL){cout << pHead->key << " ";pHead = pHead->next;}cout << endl;}int main(){ListNode node1(1); ListNode node2(2); ListNode node3(3);ListNode node4(4); ListNode node6(6);node1.next = &node3;node3.next = &node2;node2.next = &node4;node4.next = &node6;cout << "排序前的链表:";showList(&node1);//排序之前cout << "排序后的链表:";showList(ListMergeSort(&node1));//排序之后return 0;}