c语言:创建环状链表

/*
	要创建一个环形链表,创建十个节点并赋值0-9,并依次输出
*/
#include <stdio.h>
#include <malloc.h>
#define N 10
struct node
{
    int num;
    struct node* next;
};
struct node*create()//方法是尾插法,也就是头指针一直不变,从尾部插入创建节点
{
    int i=0;
    struct node*head=NULL;
    struct node*q=NULL;
    head=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    head->num=i;
    if(head==NULL)
        printf("NULL");
    struct node*tail=head;//创建第一个节点,并让head和tail指向的是同样的节点
    for(i=1;i<N;i++)//循环创建其他九个节点
    {
        q=(struct node*)malloc(sizeof(struct node));
        q->num=i;
        q->next=NULL;//q指向的是最后一个节点
        tail->next=q;//将p和tail关联,使p连进链表中
        tail=q;//让tail指回尾部
    }
    //到此是创建了一个单向链表
    tail->next=head;//最后让“头尾相连”
    return (head);//返回头指针
}
int main()
{
    struct node *p=create();//p指针指向以创建的链表的头指针
    int i;
    for(i=0;i<N;i++)
    {
        printf("%d  ",p->num);//依次输出数据
        p=p->next;
    }
}

现在来看看结果

因为是环状链表,所以输出100个的时候就是把0-9循环了10次
在这里插入图片描述

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值