n个人想玩残酷的死亡游戏,游戏规则如下:
n个人进行编号,分别从1到n,排成一个圈,顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,活到最后的一个人是胜利者。
请输出最后一个人的编号。
输入格式:
输入n和m值。 (1<=n<=100 , 1<=m<=100)
输出格式:
输出胜利者的编号。
输入样例:
5 3
输出样例:
4
Hint
第一轮:3被杀
第二轮:1被杀
第三轮:5被杀
第四轮:2被杀
#include <stdio.h>
#include <stdlib.h>
struct node {
int id;
struct node* next;
};
struct node* creat(int n);
int sel(struct node* head, int m,int n);
int main() {
int n, m,q;
struct node* head;
scanf("%d%d", &n, &m);
head = creat(n);
q = sel(head,m,n);
printf("%d\n", q);
return 0;
}
struct node* creat(int n) {
struct node* p, * q, * head;
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
head->id = 1;
q = head;
int i;
for (i = 2; i <= n; i++) {
p = (struct node*)malloc(sizeof(struct node));
p->next = NULL;
p->id = i;
q->next = p;
q = p;
}
q->next = head;
return(head);
}
int sel(struct node*head,int m,int n)
{
int num=0;//报数
int count=0;//出圈数
struct node*p,*q;//分别指向当前结点及其前驱结点的指针
q=head;//因为我想从第一个结点开始找,所以还要一个前驱结点,而第一个结点的前驱结点是尾结点
while(q->next!=head)//这三步是为了找到尾结点,安置前驱指针,使前驱指针指向尾结点
q=q->next;
while(count<n-1)
{
p=q->next;
num++;
if(num%m==0)//找到一个被删结点,完成删除、计数、输出
{
q->next=p->next;
free(p);
count++;
}
else
q=p;
}
return q->id;
}