2.试以单链表为存储结构,实现简单选择排序算法。算法提示如下: void LinkedListSelectSort(LinkedList head) //本算法一趟找出一个关键字最小的结点,其数据和当前结点进行交换;若要交换指针,则须记下当前结点和最小结点的前驱指针
时间: 2024-03-22 15:42:14 浏览: 53
好的,下面是以单链表为存储结构,实现简单选择排序算法的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结构体
typedef struct Node {
int data;
struct Node* next;
} LinkedList, *pLinkedList;
// 创建单链表节点
pLinkedList createNode(int data) {
pLinkedList node = (pLinkedList)malloc(sizeof(LinkedList));
node->data = data;
node->next = NULL;
return node;
}
// 插入节点到单链表头部
void insertNode(pLinkedList* head, int data) {
pLinkedList node = createNode(data);
node->next = *head;
*head = node;
}
// 交换两个节点的数据
void swap(pLinkedList a, pLinkedList b) {
int temp = a->data;
a->data = b->data;
b->data = temp;
}
// 单链表实现选择排序
void LinkedListSelectSort(pLinkedList head) {
pLinkedList current = head;
pLinkedList min_node = NULL, min_prev = NULL;
while (current != NULL) {
min_node = current;
pLinkedList iterator = current->next;
while (iterator != NULL) {
if (iterator->data < min_node->data) {
min_node = iterator;
min_prev = current;
}
iterator = iterator->next;
}
if (current != min_node) {
swap(current, min_node);
if (min_prev != NULL) {
swap(current->next, min_node->next);
} else {
pLinkedList temp = current->next;
current->next = min_node->next;
min_node->next = temp;
head = min_node;
}
}
current = current->next;
}
}
// 输出单链表
void printList(pLinkedList node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
pLinkedList head = NULL;
// 插入节点到单链表
insertNode(&head, 6);
insertNode(&head, 7);
insertNode(&head, 3);
insertNode(&head, 8);
insertNode(&head, 2);
insertNode(&head, 1);
insertNode(&head, 5);
insertNode(&head, 4);
printf("原始链表:\n");
printList(head);
// 选择排序
LinkedListSelectSort(head);
printf("\n排序后的链表:\n");
printList(head);
return 0;
}
```
LinkedListSelectSort 函数使用简单选择排序算法排序单链表,使用 min_prev 变量记录当前最小节点的前驱节点,当 min_prev 不为空时,则交换当前节点和最小节点的指针,否则直接交换两个节点的指针。printList 函数用于输出链表的每个元素。
阅读全文