有c++写链表的插入程序 说明 第一个参数链表指针,有一个空白链表的指针 第二个参数,插入链表的位置,整形 第三个参数,插入链表的值。
时间: 2023-04-12 21:00:35 浏览: 46
以下是一个C语言写链表插入程序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int value;
struct Node* next;
} Node;
// 插入节点到链表中
void insertNode(Node** head, int position, int value) {
// 创建新节点
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->value = value;
newNode->next = NULL;
// 如果链表为空,则直接将新节点作为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 如果插入位置为0,则将新节点作为头节点
if (position == 0) {
newNode->next = *head;
*head = newNode;
return;
}
// 找到插入位置的前一个节点
Node* prev = *head;
for (int i = 0; i < position - 1; i++) {
if (prev->next == NULL) {
printf("插入位置超出链表长度\n");
return;
}
prev = prev->next;
}
// 插入新节点
newNode->next = prev->next;
prev->next = newNode;
}
int main() {
// 创建空白链表
Node* head = NULL;
// 插入节点到链表中
insertNode(&head, 0, 1);
insertNode(&head, 1, 3);
insertNode(&head, 1, 2);
insertNode(&head, 3, 4);
// 遍历链表并输出
Node* current = head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
return 0;
}
```
以上代码实现了一个简单的链表插入程序,可以根据传入的参数将新节点插入到链表的指定位置。
相关推荐
![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)