#include<stdio.h>
#include<malloc.h>
/*约瑟夫问题--底层实现:动态队列*/
//定义队列结点类型
typedef struct People{
int data;
struct People *next;
}People;
//定义队列类型
typedef struct Node{
People *head;
People *tail;
}Queue;
int main(){
People *New,*temp;
Queue queue;
int n,p;
int i=1;
New = (People*)malloc(sizeof(People));
New->next = NULL;
queue.head = New;
queue.tail = queue.head;
//n表示人数,p表示每次第p个人出局
scanf("%d%d",&n,&p);
//初始化队列
while(i<=n){
New = (People*)malloc(sizeof(People));
New->data = i;
New->next = NULL;
queue.tail->next = New;
queue.tail = New;
i++;
}
New = queue.head->next;
while(New!=NULL){
i = 1;
while(i<p){
queue.tail->next = New;
queue.tail = New;
New = New->next;
queue.tail->next=NULL;
i++;
}
printf("%d ",New->data);
temp = New->next;
free(New);
New = temp;
}
return 0;
}
网友评论