写一个c++的程序链表的插入程序 说明 第一个参数链表指针,有一个空白链表的指针 第二个参数,插入链表的位置,整形 第三个参数,插入链表的值。
时间: 2023-04-05 21:05:25 浏览: 87
以下是一个示例程序,可以实现链表的插入操作:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int position, int value) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = value;
new_node->next = NULL;
if (position == 1) {
new_node->next = *head_ref;
*head_ref = new_node;
return;
}
struct Node* prev_node = *head_ref;
for (int i = 1; i < position - 1; i++) {
prev_node = prev_node->next;
}
new_node->next = prev_node->next;
prev_node->next = new_node;
}
int main() {
struct Node* head = NULL;
insert(&head, 1, 10);
insert(&head, 2, 20);
insert(&head, 3, 30);
insert(&head, 2, 15);
struct Node* current_node = head;
while (current_node != NULL) {
printf("%d ", current_node->data);
current_node = current_node->next;
}
return 0;
}
```
这个程序中,我们定义了一个 `Node` 结构体,表示链表中的一个节点。`insert` 函数接受三个参数:链表头指针、插入位置和插入值。它会创建一个新的节点,并将其插入到链表中指定的位置。在 `main` 函数中,我们演示了如何使用 `insert` 函数来插入四个节点,并打印出整个链表的值。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)