c语言之单链表的创建与应用

1.定义结构体 

#include
//定义结构体
struct node{
    int data;
    struct node* next;
};

2.创建链表

struct node* creatlist()
{
    struct node* headnode = (struct node*)malloc(sizeof(struct node));
    //headnode 成为了结构体变量
    //变量使用前必须被初始化
    //headnode->data =1;
    headnode->next =NULL;
    return headnode;
} 

3.创建结点(结构体变量)

struct node* createnode(int data)
{
    struct node* newnode = (struct node*)malloc(sizeof(struct node));
    newnode->data = data;
    newnode->next = NULL;
    return newnode;
}

4.打印结点

void printlist(struct node* headnode)
{
    struct node* pr = headnode->next;
    while(pr->next!=NULL)
    {
      printf("%d",pr);
      pr = pr->next;
    }
    printf("\n");
}

5.插入结点、参数;插入那个链表,插入的结点的数据是多少

void insertnodebyhead(struct node* headnode,int data)
{
    struct node* newnode = createnode(data);    //通过调用子函数,创建结点
    newnode->next = headnode->next;      //头插法,headnode->next为下一个结点(表头下一个结点)的地址,newnode的指针域指向下一个结点(地址)
    headnode->next = newnode;     // 原表头指向新建的结点(地址)
}

6.主函数main

int main()
{
    struct node* list = createlist();
    insertnodebyhead(list,1);
    insertnodebyhead(list,2);
    insertnodebyhead(list,3);
    printlist(list);
    system("pasue");
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值