已知链表L有序递增,用C语言编写程序,将X插入链表的适当位置上,以保持链表的有序性
时间: 2024-03-13 19:19:47 浏览: 81
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void insert(Node** head, int x) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = x;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
return;
}
if (x < (*head)->data) {
new_node->next = *head;
*head = new_node;
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data < x) {
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
void print_list(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
int main() {
Node* head = NULL;
insert(&head, 1);
insert(&head, 3);
insert(&head, 5);
insert(&head, 7);
insert(&head, 9);
printf("Original list: ");
print_list(head);
insert(&head, 6);
printf("\nList after inserting 6: ");
print_list(head);
return 0;
}
```
阅读全文