用C语言实现单链表插入时进行排序
时间: 2024-05-09 07:21:31 浏览: 11
可以使用头插法或者尾插法来实现单链表的插入排序。具体实现方法可以参考以下代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void insert(Node** head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
Node* curr = *head;
Node* prev = NULL;
while (curr != NULL && curr->data < data) {
prev = curr;
curr = curr->next;
}
if (prev == NULL) {
newNode->next = *head;
*head = newNode;
} else {
prev->next = newNode;
newNode->next = curr;
}
}
void printList(Node* head) {
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
insert(&head, 3);
insert(&head, 1);
insert(&head, 5);
insert(&head, 2);
insert(&head, 4);
printList(head);
return 0;
}
```