#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
Node *next;
}CLink;
void print(CLink *pNode);
//初始化
void Init(CLink **Node)//初始化循环链表,注意指针的使用
{
int n,a;
CLink *sta,*temp;
printf("输入元素个数:\n");
scanf("%d",&n);
while(n--)
{
scanf("%d",&a);
if(!(*Node))//若链表为空,生成头结点
{
(*Node)=(CLink *)malloc(sizeof(CLink));
(*Node)->data=a;
(*Node)->next=(*Node);
}
else
{
for(sta=(*Node);sta->next!=(*Node);sta=sta->next);//寻找指向pNode的最后一个节点
temp=(CLink *)malloc(sizeof(CLink));//插入当前结点
temp->data=a;
temp->next=sta->next;
sta->next=temp;
}
print(*Node);//插入一次后,打印当前链表
}
}
void print(CLink *pNode)//打印链表
{
printf("print:");
CLink *temp=pNode;
while(temp->next!=pNode)
{
printf("%d->",temp->data);
temp=temp->next;
}printf("%d",temp->data);
printf("\n");
//free(temp);
}
int main()
{
CLink *l=NULL;
Init(&l);
print(l);
}
运行结果: