在建立单链表的基础上注意把 p->next=NULL改为p->next=head;(输出同理)
喜欢撸代码:
/*循环链表 circular linked list*/
/*lenth=n*/
#include<stdio.h>
#include<iostream>
using namespace std;
struct node
{
int data;
node *nex;
};
void input_cir(node *head,int n)
{
node *p=head->nex;
while(n)
{
n--;
node *q=new node;
scanf("%d",&q->data);
p->nex=q;
q->nex=head;/*尾部为表头位置*/
p=q;
}
return;
}
void find_cir(node *head,int n)
{
node *p=head->nex;
int t=0;
printf("输出两遍循环链表:\n");
while(t<=2*n)
{
printf("%d ",p->data);
/*循环输出链表 不过由于head->data 无值,所以中间会有一个大数(乱码)*/
p=p->nex;
t++;
}
printf("\n输出循环链表:\n");
p=head->nex;
while(p!=head)/*注意结束条件*/
{
printf("%d ",p->data);
p=p->nex;
}
printf("\n");
return;
}
int main()
{
int n;
scanf("%d",&n);
node *head=new node;
head->nex=head;
input_cir(head,n);
find_cir(head,n);
return 0;
}