利用前面的实验建立一个有序的单链表L={5,12,14,18,23,34},然后将元素15插入到单链表中,要求单链表还是有序的单链表,最后依次显示当前单链表中的数据元素。c语言
时间: 2024-05-10 08:20:29 浏览: 28
代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
void insert(Node* head, int x) {
Node* p = head;
while (p->next != NULL && p->next->data < x) {
p = p->next;
}
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = x;
new_node->next = p->next;
p->next = new_node;
}
void display(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int a[] = {5, 12, 14, 18, 23, 34};
int n = sizeof(a) / sizeof(int);
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
for (int i = 0; i < n; i++) {
insert(head, a[i]);
}
insert(head, 15);
display(head);
return 0;
}
```
输出结果为:5 12 14 15 18 23 34
阅读全文