使用c++写链表的插入程序 其中 第一个参数链表指针,有一个空白链表的指针 第二个参数,插入链表的位置,整形 第三个参数,插入链表的值。
时间: 2023-04-12 13:00:47 浏览: 61
以下是使用 C 语言写链表插入程序的代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node* next;
};
// 插入链表节点
void insertNode(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;
// 如果插入位置为 1,直接将新节点插入到链表头部
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;
if (prev_node == NULL) {
printf("插入位置无效\n");
return;
}
}
// 插入新节点
new_node->next = prev_node->next;
prev_node->next = new_node;
}
// 打印链表
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
// 创建空白链表
struct Node* head = NULL;
// 插入节点
insertNode(&head, 1, 10);
insertNode(&head, 2, 20);
insertNode(&head, 3, 30);
insertNode(&head, 4, 40);
// 打印链表
printList(head);
return 0;
}
```
以上代码可以实现在链表的任意位置插入节点。如果插入位置无效,程序会输出提示信息。