单链表插入排序 C语言
时间: 2023-07-09 19:40:18 浏览: 105
以下是单链表插入排序的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void insert(Node** head_ref, int data) {
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->data = data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
void insertionSort(Node** head_ref) {
Node* sorted = NULL;
Node* current = *head_ref;
while (current != NULL) {
Node* next = current->next;
if (sorted == NULL || sorted->data >= current->data) {
current->next = sorted;
sorted = current;
} else {
Node* temp = sorted;
while (temp->next != NULL && temp->next->data < current->data) {
temp = temp->next;
}
current->next = temp->next;
temp->next = current;
}
current = next;
}
*head_ref = sorted;
}
int main() {
Node* head = NULL;
insert(&head, 5);
insert(&head, 20);
insert(&head, 4);
insert(&head, 3);
insert(&head, 30);
printf("原链表:\n");
printList(head);
insertionSort(&head);
printf("\n排序后的链表:\n");
printList(head);
return 0;
}
```
这里使用了链表的头插法来构建单链表,然后使用插入排序对链表进行排序。插入排序的时间复杂度为 O(n^2),但是对于链表这种数据结构来说,插入排序是一种比较好的排序方法。
阅读全文