在链表的任意位置插入一个节点

思路

设计一个 Insert(int data,int n) 函数,使得一个存有该数据的节点能够插入第n个位置。

代码实现

设计一个 Insert 函数,一个 Print 函数 以及 main 函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head;//定义一个全局变量head,使所有的函数都能够调用,无需传参。
void Insert (int data,int n){
struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node));
temp1->data = data;
temp1->next = NULL;
if(n==1){
temp1->next = head;
head = temp1;
return;
}
struct Node* temp2 = head;
for(int i=0;i<n-2;i++){
temp2 = temp2->next;//循环后的temp2是第n-1个Node的地址,也是第n-2个Node的next值
}
temp1->next = temp2->next;
temp2->next = temp1;//第n-1个Node的next更改为插入Node的地址
}
void Print(){
struct Node* temp = head;
while(temp != NULL){
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
head = NULL;
printf("How many numbers?\n");
int n,i,number,position;
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter the number and position\n");
scanf("%d%d",&number,&position);
Insert(number,position);
Print();
}
return 0;
}
作者

MiYan

发布于

2023-01-02

更新于

2023-01-02

许可协议