数据结构——练习之约瑟夫环问题
约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。很简单,直接附上代码了:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
/**定义人的数据对象的结构体**/
struct node{
int id;
struct node *next;
};
typedef struct node NodeList;
/**函数声明**/
NodeList* InitList(int n);
void FindM(NodeList *list,int m,int n);
/**初始化**/
NodeList* InitList(int n){
NodeList *head,*pre,*p;
head = (NodeList *)malloc(sizeof(NodeList));
head->next = NULL;
head->id = 1;
pre = head;
for(int i =2;i<=n;i++){
p = (NodeList *)malloc(sizeof(NodeList));
p->id = i;
pre->next = p;
pre = p;
}
p->next = head;
return head;
}
/**剔除数到m的人**/
void FindM(NodeList *list,int m,int n){
NodeList *pre = list;
NodeList *p;
int i = 1;
while(pre->id!=pre->next->id){
if(i==m-1){
p = (NodeList *)malloc(sizeof(NodeList));
p = pre ;
}else if(i==m){
p->next = pre->next;
printf("Delete %d\n",pre->id);
n--;
i=0;
}
i++;
pre = pre->next;
}
printf("Delete %d\n",pre->id);
}
void main(){
NodeList *h;
int n,m;
printf("Input the number of people:");
scanf("%d",&n);
printf("Input the number to count:");
scanf("%d",&m);
h = InitList(n);
FindM(h,m,n);
system("pause");
}