单链表使用方法

1.链表节点结构体创建

 struct node
{
    int data;
    struct node *next;
}

2.创建一个头结点并初始化

void init_linklist(struct node *phead)
{
    phead->data = 0;
    phead->next = NULL;
    return;
}

3.在尾部插入数据

bool insert_val_tail(struct node *phead, int val)  //尾部插入
{
    struct node *pnew = (struct node *)malloc(sizeof(struct node));  //堆区创建一个新节点
    if (!pnew)   //堆区如果内存已满则创建失败
    return false;
    pnew->data = val;
    pnew->next = NULL;

    struct node *pcur;  //定义一个临时变量
    for (pcur = phead; pcur->next != NULL; pcur = pcur->next)  //找到最后一个节点
    {
    }
    
    pcur->next = pnew;  //连接到新节点
    return true;
}

4.遍历链表

void print_linklist(struct node *phead)
{
    struct node *pcur;
    for (pcur = phead->next; pcur != NULL; pcur = pcur->next)  //从第一个节点开始遍历
    {
        printf("%d---->", pcur->data);
    }
    putchar('\n');
}

5.main函数赋值并打印数据

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int main()
{
    struct node head;   //定义结构体变量
    init_linklist(&head);  //初始化头节点
    insert_val_tail(&head, 10); //尾部插入数据
    insert_val_tail(&head, 20);
    insert_val_tail(&head, 30);
    print_linklist(&head);   //打印链表数据

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值