请用C++或者C语言设计有序整数单链表的插入运算程序,并用相关数据进行测试 输入按升序顺序输入单链表A的各个元素和待插入元素输出第一行:创建单链表A后,输出所有元素 第二行:输出按照升序插入后的所有元素
时间: 2023-04-12 17:00:23 浏览: 136
以下是C语言设计有序整数单链表的插入运算程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int n) {
Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node *node = (Node *) malloc(sizeof(Node));
scanf("%d", &node->data);
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
void printList(Node *head) {
for (Node *p = head; p != NULL; p = p->next) {
printf("%d ", p->data);
}
printf("\n");
}
void insertNode(Node **head, int x) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = x;
node->next = NULL;
if (*head == NULL) {
*head = node;
} else if (x < (*head)->data) {
node->next = *head;
*head = node;
} else {
Node *p = *head;
while (p->next != NULL && p->next->data < x) {
p = p->next;
}
node->next = p->next;
p->next = node;
}
}
int main() {
int n, x;
scanf("%d", &n);
Node *head = createList(n);
scanf("%d", &x);
insertNode(&head, x);
printList(head);
return 0;
}
```
测试数据:
```
5
1 3 5 7 9
4
```
输出结果:
```
1 3 4 5 7 9
```
注意:这个程序只是一个示例,实际应用中需要根据具体需求进行修改和优化。
阅读全文