使用c++实现链表的插入
时间: 2023-05-22 07:03:28 浏览: 59
在链表中插入元素需要执行以下步骤:
1. 分配空间
2. 将新元素的下一个指针指向插入位置的当前元素
3. 将插入位置前一个元素的指针指向新元素。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
void insertNode(Node **head, int data, int position){
Node* temp1 = malloc(sizeof(Node));
temp1->data = data;
temp1->next = NULL;
if(position == 1){
temp1->next = *head;
*head = temp1;
return;
}
Node* temp2 = *head;
for(int i = 0; i < position - 2; ++i){
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
int main(){
Node* head = NULL;
insertNode(&head, 2, 1);
insertNode(&head, 3, 2);
insertNode(&head, 4, 1);
insertNode(&head, 8, 2);
Node* temp = head;
while(temp != NULL){
printf("%d ", temp->data);
temp = temp->next;
}
return 0;
}
```
输出结果为:4 8 2 3