尾插法初始化链表的两种方式

方法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);
}

结果:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值