请写一个双向链表的快速排序函数
// 双向链表节点结构
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
// 交换两个节点的数据
void swap(Node* a, Node* b) {
int temp = a->data;
a->data = b->data;
b->data = temp;
}
// 分区函数,返回基准节点的位置
Node* partition(Node* low, Node* high) {
int pivot = high->data; // 选择最后一个节点作为基准
Node* i = low->prev; // i 是小于基准的部分的最后一个节点
for (Node* j = low; j != high; j = j->next) {
if (j->data <= pivot) {
i = (i == NULL) ? low : i->next; // 移动 i
swap(i, j); // 交换 i 和 j 的数据
}
}
i = (i == NULL) ? low : i->next; // 移动 i
swap(i, high); // 将基准节点放到正确的位置
return i;
}
// 快速排序递归函数
void quickSort(Node* low, Node* high) {
if (high != NULL && low != high && low != high->next) {
Node* pivot = partition(low, high); // 获取基准节点
quickSort(low, pivot->prev); // 递归排序左半部分
quickSort(pivot->next, high); // 递归排序右半部分
}
}
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// 在链表尾部插入节点
void insertAtEnd(Node** head, Node** tail, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = *tail = newNode;
} else {
(*tail)->next = newNode;
newNode->prev = *tail;
*tail = newNode;
}
}
// 打印链表
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 释放链表内存
void freeList(Node* head) {
Node* current = head;
while (current != NULL) {
Node* next = current->next;
free(current);
current = next;
}
}
int main() {
Node* head = NULL;
Node* tail = NULL;
int num;
printf("请输入一串数字(以空格分隔,以任意非数字字符结束输入):\n");
// 输入数字并插入链表
while (scanf("%d", &num) == 1) {
insertAtEnd(&head, &tail, num);
}
// 清空输入缓冲区
while (getchar() != '\n');
printf("原始链表: ");
printList(head);
// 对链表进行快速排序
quickSort(head, tail);
printf("排序后的链表: ");
printList(head);
// 释放链表内存
freeList(head);
return 0;
}