|
发表于 2023-12-15 20:02:13
|
显示全部楼层
好的,下面是一个使用链表实现快速排序的示例代码:
- #include <stdio.h>
- #include <stdlib.h>
- // 定义链表结点
- struct Node {
- int data;
- struct Node* next;
- };
- // 创建新结点
- struct Node* newNode(int data) {
- struct Node* node = (struct Node*)malloc(sizeof(struct Node));
- node->data = data;
- node->next = NULL;
- return node;
- }
- // 分割链表,并返回分割点
- struct Node* partition(struct Node* head, struct Node* end, struct Node** newHead, struct Node** newEnd) {
- struct Node* pivot = end;
- struct Node* prev = NULL;
- struct Node* cur = head;
- struct Node* tail = pivot;
- while (cur != pivot) {
- if (cur->data < pivot->data) {
- if (*newHead == NULL) {
- *newHead = cur;
- }
- prev = cur;
- cur = cur->next;
- } else {
- if (prev) {
- prev->next = cur->next;
- }
- struct Node* temp = cur->next;
- cur->next = NULL;
- tail->next = cur;
- tail = cur;
- cur = temp;
- }
- }
- if (*newHead == NULL) {
- *newHead = pivot;
- }
- *newEnd = tail;
- return pivot;
- }
- // 快速排序链表
- struct Node* quickSort(struct Node* head, struct Node* end) {
- if (!head || head == end) {
- return head;
- }
- struct Node* newHead = NULL;
- struct Node* newEnd = NULL;
- struct Node* pivot = partition(head, end, &newHead, &newEnd);
- if (newHead != pivot) {
- struct Node* temp = newHead;
- while (temp->next != pivot) {
- temp = temp->next;
- }
- temp->next = NULL;
- newHead = quickSort(newHead, temp);
- temp = newHead;
- while (temp->next) {
- temp = temp->next;
- }
- temp->next = pivot;
- }
- pivot->next = quickSort(pivot->next, newEnd);
- return newHead;
- }
- // 打印链表
- void printList(struct Node* head) {
- while (head) {
- printf("%d ", head->data);
- head = head->next;
- }
- printf("\n");
- }
- int main() {
- // 创建链表
- struct Node* head = newNode(4);
- head->next = newNode(2);
- head->next->next = newNode(1);
- head->next->next->next = newNode(3);
- printf("原始链表:");
- printList(head);
- head = quickSort(head, NULL);
- printf("排序后链表:");
- printList(head);
- return 0;
- }
复制代码
在这个例子中,我们先定义了一个链表结点`Node`,其中包含一个整数型的数据成员和指向下一个结点的指针。然后,我们实现了`newNode`函数用于创建新结点。
接下来,我们定义了两个辅助函数`partition`和`quickSort`。`partition`函数用于分割链表,并返回分割点,它接收链表的头结点、尾结点和两个指针的指针作为参数(用于更新链表的头结点和尾结点)。
`quickSort`函数用于快速排序链表,它递归地调用`partition`函数,并根据分割点将链表划分为两部分进行排序。
最后,在`main`函数中,我们创建了一个包含4个结点的链表,并调用`quickSort`函数对链表进行排序,并打印排序后的链表。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|