#include <iostream> #include <ctime> #define LEN 20 #define MAX_VAL 100 using namespace std; // 链式结构元素 struct elem { elem() { value = 0; next = NULL; } int value; elem * next; }; // 链式结构 struct node { node() { head = tail = NULL; } elem* head; elem* tail; }; // 比较函数 int compare_node(elem* elem_1, elem* elem_2) { if(elem_1->value < elem_2->value) { return -1; } else if(elem_1->value == elem_2->value) { return 0; } else { return 1; } } /* 对链式结构进行快速排序的partition函数, 输入是待排序链表表头 返回值首元素在partition后所在的位置的指针 需要对head进行修改, tail不用修改, tail不包含在本段内, 因此与tail无缝对接 */ elem* partition(elem** head, elem* tail, int sort_type) { elem* newHead = *head; // 本段新的链表头 elem* headPtr = *head; // 保存中间元素的位置的指针 elem* curPtr = (*head)->next; // 前驱指针 elem* prePtr = *head; while(curPtr != tail) // 遍历当前段, 直到哨兵末尾位置 { if(compare_node(headPtr, curPtr) == sort_type) { prePtr->next = curPtr->next; curPtr->next = newHead; newHead = curPtr; curPtr = prePtr->next; } else { prePtr = curPtr; curPtr = curPtr->next; } } *head = newHead; return headPtr; } // 快速排序, sort_type = -1: 升序, 1:降序, tail不被包含在当前段 void quickSort(elem** head, elem* tail, int sort_type) { //单元素段, 直接返回 if(*head == tail) return; // 划分, mid是首元素划分后所在位置 elem* mid = partition(head, tail, sort_type); elem** head_1 = head; elem** head_2 = &mid->next; // 二分 quickSort(head_1, mid, sort_type); quickSort(head_2, tail, sort_type); // 将mid之前(包括mid)段与右侧新段重新连接 mid->next = *head_2; // 修改mid左侧段的首指针 *head = *head_1; } int main() { node* nptr = new node(); srand(time(NULL)); for(int i = LEN; i >= 1; i--) { int value = rand() % MAX_VAL + 1; if(nptr->head == NULL) { nptr->head = nptr->tail = new elem(); nptr->head->value = value; } else { elem* tempPtr = new elem(); tempPtr->value = value; nptr->tail->next = tempPtr; nptr->tail = nptr->tail->next; } } //排序 elem** tempHead = &(nptr->head); quickSort(tempHead, NULL, -1); nptr->head = *tempHead; //打印排序后的串 elem* tempPtr = nptr->head; while(tempPtr) { cout<<tempPtr->value<<" "; tempPtr = tempPtr->next; } cout<<endl; return 0; }