单循环链表.c

来自「对一个链表实现循环」· C语言 代码 · 共 52 行

C
52
字号
#include <stdio.h>

 /*创建一个能调用自身的结构*/
 typedef struct cnode
{
 int date;
 struct cnode *next;
}cnode,*linklist;

void main()
{

 int m,n,i,j=1;
 cnode *h,*p,*s;
 /*以下语句提示用户输入合法的M,N值*/
 printf("\nInput the total number of the monkeys (m):\t");
 scanf("%d",&m);
 printf("Input the integer number n (n<m):\t");
 scanf("%d",&n);
 while(n<1||n>m)
 {printf("Error,ReIuput:");scanf("%d",&n);};


 /*实现循环链表,并给节点赋值*/
 for(i=0;i<m;i++)
 {
  s=(linklist)malloc(sizeof(cnode));
  s->date=i+1;
  if(i==0) {h=s;p=h;s->next=NULL;}
  else  {p->next=s;p=p->next;}
  };
 p->next=h;

/*当N为1时,输出编号为M的猴子为大王*/
if(n==1)
printf("The monkey whose serial number is %d is the king. \n",m);

/*当N不为1时,计算出为大王的猴子编号*/
else
{
p=h;
while(p->next!=p)
{
 while(j<n-1) {p=p->next; j++;}
 s=p->next; p->next=s->next;free(s);j=1;p=p->next;
}
printf("The monkey whose serial number is %d is the king \n",p->date);

}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?