方法1:(通过值传递来初始化)
#include<stdio.h>
#include<stdlib.h>
struct node //定义结构体
{
int name;//结构体里面定义一个变量叫做name
struct node *next;
};
struct node *node_init(struct node *f1, struct node *f2, int i)
{
f2->name = i-1;
f2->next = f1->next;
f1->next = f2;
f1 = f2;
return f1;
}//注意:这里不能使用void类型,这个函数改变的是f1的指向改变的并不是主函数index的指向
因此,这个函数必须有返回值,用返回值来改变index的指向
void print_node(struct node *f1) //定义一个函数通过头节点打印出链表
{
if (f1->next == NULL)
return;
f1 = f1->next;
while (f1 != NULL)
{
printf("%d ", f1->name);
f1 = f1->next;
}
printf("\n");
}
int main()
{
struct node head;
struct node *index = &head; //定义一个指针变量index指向head
head.next = NULL;
int i = 0;
for (i = 0; i < 5; i++) //初始化链表
{
struct node *p = malloc(sizeof(struct node));
index = node_init(index, p, i + 2);
}
print_node(&head);
}
结果:
方法2(通过二级指针来初始化)
#include<stdio.h>
#include<stdlib.h>
struct node //定义结构体
{
int name;//结构体里面定义一个变量叫做name
struct node *next;
};
void node_init(struct node **f1, struct node *f2, int i)//定义一个二
级指针来存index的地址通过地址传递来改变index的指向
{
f2->name = i-1;
f2->next = (*f1)->next;
(*f1)->next = f2;
*f1 = f2;
}
void print_node(struct node *f1) //定义一个函数通过头节点打印出链表
{
if (f1->next == NULL)
return;
f1 = f1->next;
while (f1 != NULL)
{
printf("%d ", f1->name);
f1 = f1->next;
}
printf("\n");
}
int main()
{
struct node head;
struct node *index = &head; //定义一个指针变量index指向head
head.next = NULL;
int i = 0;
for (i = 0; i < 5; i++) //初始化链表
{
struct node *p = malloc(sizeof(struct node));
node_init(&index, p, i + 2);
}
print_node(&head);
}
结果: