高分解答约瑟夫环程序注解

来源:百度知道 编辑:UC知道 时间:2024/05/15 06:46:24
请在//后添加注释即可

采用单向循环链表实现约瑟夫环
从键盘输入整数m,生成一个具有m个结点的单向环表。环表中的结点编号依次为1,2,~m。
从键盘输入整数s(1<=s<=m)和n,从环表的第s个结点开始计数为1,当计数到第n个结点时,输出该第n结点对应的编号,将该结点从环表中消除,从输出结点的下一个结点开始重新计数到n,这样,不断进行输出,直到输出了这个环表的全部结点为止。
例如:m=10,s=3,n=4。则输出序列为:6,10,4,9,5,2,1,3,8,7。

#include"stdio.h"
#include"malloc.h"
struct node //
{int data;
struct node *next;
}
main()
{
int i,j,b=0,N,m,s;
struct node *p,*head,*q;
printf("input three number:\n");
scanf("%d %d %d",&m,&s,&N);
head=(struct node*)malloc(sizeof(struct node)); //
head->data=s;
head->next=head; //
for(i=m;i>0;i--) //
{
p=(struct node*)malloc(sizeof(struct node));
p->next=head->next;
p->data=i;
head->next=p;
}
while(p->next!=head)
p=p->next;
p->next=head->next; //
for(i=1;i<s;i++)
p=p->next;

#include"stdio.h"
#include"malloc.h"

struct node // 结构体定义,把环中的每个数都存放在节点中,节点之间通过next指针相连
{
int data;
struct node *next;
}
main()
{
int i,j,b=0,N,m,s;
struct node *p,*head,*q;

printf("input three number:\n");
scanf("%d %d %d",&m,&s,&N);

head=(struct node*)malloc(sizeof(struct node)); // 为头节点分配空间
head->data=s;
head->next=head; // 构造循环链表

for(i=m;i>0;i--) // 创建十个节点,赋值为1~m,同时加每个节点加入循环链表
{
p=(struct node*)malloc(sizeof(struct node));
p->next=head->next;
p->data=i;
head->next=p;
}

while(p->next!=head)
p=p->next;
p->next=head->next; // 将p指针定位到最后一个节点,并将头节点脱离出循环链表
for(i=1;i<s;i++)
p=p->next; // 将p指针定位到第s个节点的前一个节点,如果s为1,表示值为1的节点为第一个计数的节点
for(i=0;i<m;i++)
{
for(j=1;j<N;j++)