设编号为1,2,3,……,n的n(n>0)个人按顺时针方向围坐一圈,每个人持有一个正整数密码。开始时任选一个正整数做为报数上限m,从第一个人开始顺时针方向自1起顺序报数,报到m时停止报数,报m的人出列,将他的密码作为新的m值,从他的下一个人开始重新从1报数。如此下去,直到所有人全部出列为止。令n最大值取30。要求设计一个程序模拟此过程,求出出列编号序列。

struct node   //结点结构

{

    int number; 

    int cipher; 

    struct node *next; 

};

 

 分析、代码:

建立循环链表,从末指针开始,从头指针查数,数到m,则将其序号输出,是指针指向下一位,不断循环,直到只剩下一个人时,结束,输出最后一个人的序号

#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(node)
struct node               //结点结构
{
	int number;           //人的序号
	int cipher;           // 密码
	struct node *next;    // 指向下一个节点的指针
};
struct node *creat(int N)          //创建链表
{
	struct node *head;
	struct node *p1,*p2;
	int n=0;
	int t=1;
	p1=p2=(struct node*)malloc(LEN);
	p1->number=t;
	head=NULL;
	while(t<=N)
	{
		t++;n++;
		if(n==1)head=p1;
		else p2->next=p1;
		p2=p1;
		p1=(struct node *)malloc(LEN);
		p1->number=t;
	}
	p2->next=head;
	return p2;                         //  将末位指针返回
}
void main()
{
	int m,n,count;
	node *head;
	node *p1,*p2;
	scanf("%d",&n);
	head=creat(n);                //将头指针指向末尾
	count=0;
	scanf("%d",&m);
	p1=head;
	while(1)
	{
		while(count<m)               //从1查到m
		{
			p2=p1;  
			p1=p1->next;   
			count++;
		}
		printf("%d\n",p1->number);   //输出出列人序号
		p2->next=p1->next;           //是指针指向下一位
		count=0;
		n--;
		if(n==1)                     //如果只剩下一个人跳出
			break;
		scanf("%d",&m);           //输入m值
	}
	p2=p2->next;                       //将指针指向最后剩下的一个
	printf("最后一个编号为:%d\n",p2->number);         //输出最后一个人序号
}
posted on 2011-07-01 17:19  pcoda  阅读(308)  评论(0编辑  收藏  举报