约瑟夫(Joseph)问题的一种描述是:编号为1,2,3,…,n的n个人按顺时针方向围坐一圈。每人持有一个密码(正整数)。一开始任选一个正整数作为报数上限值m,从第一个人开始按顺时针方向自1开始顺序报数,报到m时停止报数,令其出列,将他的密码作为新的m值,从他在顺时针方向上的下一个人开始重新报数,如此下去,直到所有人全部出列为止。试设计一个程序求出出列顺序。
实验要求
利用无头结点的单向循环链表存储结构模拟此过程,按照出列的顺序打印出各人的编号。
测试数据:
m的初值为20;n=7,7个人的密码依次为:3,1,7,2,4,8,4,首先m值为6(正确的出列顺序应为6,1,4,7,2,3,5)
实验提示:
程序运行后,首先要求用户指定初始报数上限值,然后读取各人的密码,可设n<=30,此题所用的循环链表中不需要“头结点”,请注意空表和非空表的界限。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node
{
int key;
int order;
struct node *next;
}Node;
void Init_Node(Node *node);
Node* Create_List(int listLength);
void Function(Node *head,int maxKey,int listLength);//实现功能的函数
void Print(Node *head);
Node* FindTail(Node* head,int listLength);
void main()
{
Node *listA;
int maxKey=20,listLength;
printf("请输入报数的上限值m和总人数n\n");scanf("%d%d",&maxKey,&listLength);
listA=Create_List(listLength);
Print(listA);
Function(listA,maxKey,listLength);
}
void Init_Node(Node *node)
{
node->next=NULL;
node->order=0;
node->key=0;
}
Node* Create_List(int listLength)
{
printf("*********正在申请一个长度为%d的不带头结点的单向循环链表*********\n",listLength);
Node *head,*tail,*newNode,*node_del;
int key,i=1;
head=(Node *)malloc(sizeof(Node));if(head==NULL) {printf("申请内存失败\n");return NULL;}
tail=head;tail->next=NULL;
while(listLength--)
{
newNode=(Node *)malloc(sizeof(Node));Init_Node(newNode);
newNode->order=i;
printf("请输入第%d个节点的密码",i++);
scanf("%d",&key);newNode->key=key;
tail->next=newNode;
tail=newNode;
}
node_del=head;
head=head->next;
tail->next=head;
free(node_del);
printf("*********单向循环链表创建完毕*********\n");
return head;
}
void Function(Node *head,int maxKey,int listLength)
{
Node *node,*node_del;node=head;int count=0,freeTimes=0;
printf("遍历中......\n所有人的出列顺序为\n");
node_del=head;
node=FindTail(head,listLength);
while(node->next!=NULL)
{
node_del=node->next;
count++;
if(count==maxKey)
{
count=0;
maxKey=node_del->key;
printf("%d ",node_del->order);
node->next=node_del->next;
free(node_del);freeTimes++;
}
else node=node->next;
if(freeTimes==listLength)break;
}
printf("出列完毕\n");
}
void Print(Node *head)
{
Node *node;
node=head;int loopTimes=-1;
while(node!=NULL)
{
if(node==head)loopTimes++;
if(loopTimes==1)break;
printf("第%d个人的密码是%d\n",node->order,node->key);
node=node->next;
}
printf("Print完毕\n");
}
Node* FindTail(Node* head,int listLength)
{
Node *node;node=head;
listLength--;
while(listLength--)
{
node=node->next;
}
return node;
}