用的循环链表

来源:互联网 发布:淘宝怎么看买家评星 编辑:程序博客网 时间:2024/06/06 14:17

Description

n个人想玩残酷的死亡游戏,游戏规则如下: 

n个人进行编号,分别从1到n,排成一个圈,顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,活到最后的一个人是胜利者。 

请输出最后一个人的编号。

Input

输入n和m值。

Output

输出胜利者的编号。

Sample Input

5 3

Sample Output

4


#include <stdio.h>#include <stdlib.h>#include <string.h>#define SE struct E *#define SE1 struct Estruct E{    int data;    struct E *next;}*head;int main(){    int i,j;    struct E *p,*q,*r;    head=(SE)malloc(sizeof(SE1));    p=(SE)malloc(sizeof(SE1));    q=(SE)malloc(sizeof(SE1));    int n,m,s;    i=1;    scanf("%d %d",&n,&m);    s=n-1;    p=head;    while(n--)    {        r=(SE)malloc(sizeof(SE1));        r->data=i++;        p->next=r;        r->next=head;        p=r;    }    q=head;    while(s--)    {        j=0;        while(j<m)        {            p=q;            q=q->next;            if(q==head)                j=j-1;            j++;        }        if(q==head)        {            p=q;            q=q->next;            p->next=q->next;        }        else            p->next=q->next;    }    p=head->next;    // while(p!=head)    // {    printf("%d ",p->data);    //   p=p->next;    // }    return 0;}

0 0