用C语言实现单链表排序
时间: 2024-01-21 18:46:16 浏览: 70
使用c语言实现单链表
4星 · 用户满意度95%
可以的,以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建节点
Node* create_node(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
// 插入节点
void insert_node(Node** head, Node* node) {
if (*head == NULL) {
*head = node;
} else {
Node* cur = *head;
Node* prev = NULL;
while (cur != NULL && cur->data <= node->data) {
prev = cur;
cur = cur->next;
}
if (prev == NULL) {
*head = node;
} else {
prev->next = node;
}
node->next = cur;
}
}
// 排序链表
void sort_list(Node** head) {
Node* cur = *head;
*head = NULL;
while (cur != NULL) {
Node* next = cur->next;
insert_node(head, cur);
cur = next;
}
}
// 打印链表
void print_list(Node* head) {
Node* cur = head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
insert_node(&head, create_node(3));
insert_node(&head, create_node(2));
insert_node(&head, create_node(5));
insert_node(&head, create_node(1));
insert_node(&head, create_node(4));
print_list(head);
sort_list(&head);
print_list(head);
return 0;
}
```
阅读全文