试以单链表为存储结构,用c语言将关键字序列【49,38,65,97,76,13,27,49–】
时间: 2024-05-03 21:20:19 浏览: 13
排序,并输出排序后的结果。
以下是使用单链表实现的关键字排序的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 单链表节点结构体
typedef struct ListNode {
int value; // 节点存储的关键字值
struct ListNode *next; // 指向下一个节点的指针
} ListNode;
// 创建具有指定值的新节点
ListNode *createNode(int value) {
ListNode *node = malloc(sizeof(ListNode));
node->value = value;
node->next = NULL;
return node;
}
// 在单链表中插入新的节点
void insertNode(ListNode **head, ListNode *node) {
if (*head == NULL) { // 链表为空,插入为头节点
*head = node;
} else {
// 找到最后一个节点,插入到其后面
ListNode *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
}
// 从单链表中删除指定值的节点
void deleteNode(ListNode **head, int value) {
ListNode *prev = NULL;
ListNode *current = *head;
while (current != NULL) {
if (current->value == value) {
if (prev == NULL) { // 删除头节点
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
break;
}
prev = current;
current = current->next;
}
}
// 释放单链表的内存
void freeList(ListNode **head) {
while (*head != NULL) {
ListNode *next = (*head)->next;
free(*head);
*head = next;
}
}
// 实现冒泡排序并返回排序后的头节点
ListNode *bubbleSortList(ListNode *head) {
if (head == NULL || head->next == NULL) {
// 链表为空或只有一个节点,无需排序,直接返回头节点
return head;
}
int swapped = 1; // 标识是否有节点交换位置
while (swapped) {
swapped = 0;
ListNode *prev = NULL;
ListNode *current = head;
while (current->next != NULL) {
if (current->value > current->next->value) {
// 相邻节点值交换
ListNode *next = current->next;
current->next = next->next;
next->next = current;
if (prev == NULL) { // 交换的是头节点和第二个节点
head = next;
} else {
prev->next = next;
}
prev = next;
swapped = 1;
} else {
prev = current;
current = current->next;
}
}
}
return head;
}
int main() {
int keywords[] = {49, 38, 65, 97, 76, 13, 27, 49};
int n = sizeof(keywords) / sizeof(keywords[0]);
// 将关键字插入单链表中
ListNode *head = NULL;
for (int i = 0; i < n; i++) {
insertNode(&head, createNode(keywords[i]));
}
// 对单链表进行排序
head = bubbleSortList(head);
// 输出排序后的结果
ListNode *current = head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
// 释放单链表内存
freeList(&head);
return 0;
}
```
代码运行结果:
```
13 27 38 49 49 65 76 97
```