c语言直接插入排序法链表
时间: 2023-12-07 17:39:37 浏览: 84
直接插入排序法链表的C语言实现如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void insertSort(Node **head) {
if (*head == NULL || (*head)->next == NULL) {
return;
}
Node *p, *q, *r;
p = (*head)->next;
(*head)->next = NULL;
while (p != NULL {
r = pnext;
q = *head;
while (q->next != NULL && q->next->data < p->data) {
q = q->next;
}
p->next = q->next;
q->next = p;
p = r;
}
}
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data p = p->next;
}
printf("\n");
}
int main() {
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
int n, x;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
Node *p = (Node *)malloc(sizeof(Node));
p->data = x;
p->next = head->next;
head->next = p;
}
printf("排序前:");
printList(head->next);
insertSort(&head);
printf("排序后:");
printList(head->next);
return 0;
}
```
阅读全文