#include <stdio.h> #include <stdlib.h>

// 定义链表节点结构体 typedef struct ListNode { int data; struct ListNode *next; } ListNode;

// 创建链表节点 ListNode* createNode(int value) { ListNode newNode = (ListNode)malloc(sizeof(ListNode)); if (newNode == NULL) { printf("Memory allocation failed.\n"); exit(1); } newNode->data = value; newNode->next = NULL; return newNode; }

// 插入节点到链表末尾 void insertNode(ListNode **head, int value) { ListNode *newNode = createNode(value); if (*head == NULL) { *head = newNode; } else { ListNode *cur = *head; while (cur->next != NULL) { cur = cur->next; } cur->next = newNode; } }

// 交换两个节点的值 void swap(ListNode *a, ListNode *b) { int temp = a->data; a->data = b->data; b->data = temp; }

// 简单选择排序 void selectionSort(ListNode *head) { ListNode *cur = head; while (cur != NULL) { ListNode *minNode = cur; ListNode *nextNode = cur->next; while (nextNode != NULL) { if (nextNode->data < minNode->data) { minNode = nextNode; } nextNode = nextNode->next; } swap(cur, minNode); cur = cur->next; } }

// 打印链表 void printList(ListNode *head) { ListNode *cur = head; while (cur != NULL) { printf("%d ", cur->data); cur = cur->next; } printf("\n"); }

// 释放链表内存 void freeList(ListNode *head) { ListNode *cur = head; while (cur != NULL) { ListNode *nextNode = cur->next; free(cur); cur = nextNode; } }

int main() { ListNode *head = NULL; int n, value;

printf("Enter the number of elements: ");
scanf("%d", &n);

printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
    scanf("%d", &value);
    insertNode(&head, value);
}

printf("Before sorting: ");
printList(head);

selectionSort(head);

printf("After sorting: ");
printList(head);

freeList(head);

return 0;
编写一个C语言算法在基于不带头结点单链表表示的待排序关键字序列上进行简单选择排序

原文地址: http://www.cveoy.top/t/topic/ibEv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录