单链表直接插入排序c
时间: 2023-12-13 16:31:18 浏览: 143
用单链表实现插入排序
以下是单链表直接插入排序的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 定义链表结构体
typedef struct List {
Node *head;
int length;
} List;
// 初始化链表
void initList(List *list) {
list->head = NULL;
list->length = 0;
}
// 在链表尾部插入节点
void append(List *list, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
} else {
Node *p = list->head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
list->length++;
}
// 打印链表
void printList(List *list) {
Node *p = list->head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 单链表直接插入排序
void insertSort(List *list) {
if (list->head == NULL || list->head->next == NULL) {
return;
}
Node *p = list->head->next;
list->head->next = NULL;
while (p != NULL) {
Node *q = list->head;
Node *pre = NULL;
while (q != NULL && q->data < p->data) {
pre = q;
q = q->next;
}
if (pre == NULL) {
list->head = p;
} else {
pre->next = p;
}
Node *tmp = p->next;
p->next = q;
p = tmp;
}
}
int main() {
List list;
initList(&list);
// 在链表尾部插入节点
append(&list, 3);
append(&list, 1);
append(&list, 4);
append(&list, 2);
append(&list, 5);
printf("排序前:");
printList(&list);
// 单链表直接插入排序
insertSort(&list);
printf("排序后:");
printList(&list);
return 0;
}
```
阅读全文