c++写链表插入程序,第一个参数链表指针,有一个空白链表的指针 第二个参数,插入链表的位置,整形 第三个参数,插入链表的值。
时间: 2023-04-12 08:00:57 浏览: 69
以下是一个简单的链表插入程序的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node* next;
};
// 插入链表节点
void insertNode(struct Node** head, int pos, int val) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = NULL;
// 如果链表为空,直接将新节点作为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 如果插入位置为0,将新节点作为头节点
if (pos == 0) {
newNode->next = *head;
*head = newNode;
return;
}
// 找到插入位置的前一个节点
struct Node* prev = *head;
for (int i = 0; i < pos - 1; i++) {
prev = prev->next;
if (prev == NULL) {
printf("插入位置无效\n");
return;
}
}
// 插入新节点
newNode->next = prev->next;
prev->next = newNode;
}
// 打印链表
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// 插入节点
insertNode(&head, 0, 1);
insertNode(&head, 1, 3);
insertNode(&head, 1, 2);
insertNode(&head, 3, 4);
// 打印链表
printList(head);
return 0;
}
```
这个程序可以在给定的链表中插入一个新节点,位置由第二个参数指定,值由第三个参数指定。如果插入位置无效,程序会输出错误信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)