(1)单链表解法:
typedef struct node{ //定义单链表结构,next指向下一个节点
int key;
node *next;
}node,*pnode;
void test(){
int n,m;
cout<<"number of people per circle n = "; cin>>n;
cout<<"the m'th person to be killed m = "; cin>>m;
cout<<"the kill list is: ";
pnode ptr = (pnode)malloc(sizeof(node)*n); //分配内存
pnode p = ptr; //p为头指针head
for(int i = 0; i < n-1; i++){ //对指针赋值
ptr->key = i+1;
ptr->next = ptr+1;
ptr = ptr->next;
}
ptr->key = n; //最后一个指针赋值为n
ptr->next = p; //最后一个指针指向head p
while(p != p->next){ //当循环链表不为空,即next不指向自身
for(int i = 0; i < m-2; i++) //数到第m-1个人
p = p->next;
cout<<p->next->key<<" "; //输出第m个人
p->next = p->next->next; //将第m-1的next指向第m+1个人,即删除第m个人
p = p->next; //p从下一个人重新计数
}
cout<<p->key<<endl;
}
(2)队列解法(利用FIFO特性)
void test2(){
queue<int> circle; //FIFO
int n = 12, m = 7;
for(int i = 0; i < n; i++)
circle.push(i+1);
while(circle.size() != 0){
for(int i = 0; i < m-1; i++){ //第m个人将被移除队列circle
int temp = circle.front();
circle.pop();
circle.push(temp);
}
cout<<circle.front()<<" ";
circle.pop();
}
}