帮我写一个在有序链表中插入数据的c++ 程序简单一点
时间: 2024-05-14 21:16:51 浏览: 13
当然,我可以帮您写一个简单的C程序来实现有序链表的插入。以下是代码:
```
#include <stdio.h>
#include <stdlib.h>
/* 定义链表节点 */
struct Node {
int data;
struct Node* next;
};
/* 插入函数 */
void insert(struct Node** head, int value) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // 创建新节点
new_node->data = value; // 设置新节点数据
new_node->next = NULL; // 设置新节点后继指针
/* 如果头指针为空,则新节点为链表第一个节点 */
if (*head == NULL) {
*head = new_node;
return;
}
/* 如果新节点小于链表第一个节点,则将新节点插入到链表头部 */
if (value < (*head)->data) {
new_node->next = *head;
*head = new_node;
return;
}
struct Node* temp = *head;
/* 寻找新节点应插入的位置 */
while (temp->next != NULL && temp->next->data < value) {
temp = temp->next;
}
/* 将新节点插入到链表中 */
new_node->next = temp->next;
temp->next = new_node;
}
/* 打印链表 */
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
int main() {
/* 初始化链表 */
struct Node* head = NULL;
/* 在链表中插入数据 */
insert(&head, 2);
insert(&head, 10);
insert(&head, 8);
insert(&head, 4);
insert(&head, 6);
/* 打印链表 */
printList(head);
return 0;
}
```
这个程序可以在有序链表中正确地插入数据,并且输出结果也是按照顺序排列的。希望这个程序可以帮到您!