/*
要创建一个环形链表,创建十个节点并赋值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次