请编写一个c++代码实现在链表中第i个节点插入一个值为x的节点
时间: 2023-05-29 08:08:06 浏览: 106
以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** headRef, int i, int x) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
if (i == 0) {
newNode->next = *headRef;
*headRef = newNode;
return;
}
struct Node* curr = *headRef;
for (int j = 0; j < i - 1; j++) {
if (curr == NULL) {
printf("Error: list index out of range\n");
return;
}
curr = curr->next;
}
newNode->next = curr->next;
curr->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;
insert(&head, 0, 1);
insert(&head, 0, 2);
insert(&head, 1, 3);
insert(&head, 3, 4);
printList(head);
// Output: 2 1 3 4
return 0;
}
```
注释:
- `struct Node` 定义了链表节点的数据结构。
- `insert` 函数用于在链表中插入一个值为 `x` 的节点,插入位置为第 `i` 个节点。如果 `i` 为 0,则在链表头部插入节点。
- `printList` 函数用于打印链表中每个节点的值。
- 在 `main` 函数中,我们测试了 `insert` 函数的功能,最终打印链表中每个节点的值。