【题目描述】
约瑟夫环问题的一种描述是:编号为1,2,……,n的n个人按照顺时针方向围坐一圈,每个人持有一个密码(正整数)。一开始任选一个正整数作为报数上限值m,从第一个人开始按顺时针方向自1开始顺序报数,报到m时停止报数,报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>
#define N 30 //n<=30;
int a[N]; //定义一个全局的数组用来存储每个人的密码
typedef struct Node{
int data; //data用来存储每个人的编号,即下标
struct Node *next;
}Node,*LNode;
LNode InitLNode(int n){
LNode p,tail;
LNode head=(LNode)malloc(sizeof(Node));
if(head==NULL)
return 0;
head->next=NULL;
head->data=n;
tail=head;
for(int i=1;i<=n;i++){
p=(LNode)malloc(sizeof(Node));
p->data=i; //给他们编号
p->next=tail->next;
tail->next=p;
tail=p;
}
tail->next=head->next;
return head->next;
}
void Dele_List(LNode List,int n,int m){
LNode p=List;
LNode tail=List;
while(p->next!=p){ // 循环遍历
for(int i=1;i<m;i++){ //遍历前m-1个节点,使得p正好指向第m个节点
tail=p;
p=p->next;
}
tail->next=p->next;
printf("出列的下标为:%d\n",p->data);
m=a[p->data]; //把第m个节点的密码赋给m
free(p); //删除第m个节点
p=tail->next;
}
printf("出列的下标为:%d\n",p->data); //因为上面那个循环并不能正好把列表中的节点释放完,最后还剩一个,需要单独释放
free(p);
}
int main(){
int n,m;
scanf("%d%d",&n,&m);
LNode List=InitLNode(n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
Dele_List(List,n,m);
return 0;
}
要点:
1.出队函数中的循环条件
2.循环并不能删除所有节点