Problem E: 用链表实现约瑟夫环

Description

你听说过约瑟夫问题吗?问题大致如下:首先n个人围成一个圈,标记为1到n号。接着,从1号开始报数(从1开始),然后2号报数,然后3号。。。当有人报到到m时,这个人就要踢出比赛,然后从被踢出的人的下一个人开始,重新报数(从1开始)。这样经过n-1次后,就只剩下了一个人,问最后剩下的那个人是几号?

 

Input

第1行为T,表示有T组数据;

第2行到第T+1开始,每行输入n和m,n表示有几个人,m为上述的每报数m次就要踢出一个人

1=<n<=100, 1=<m<=100

 

Output

一个数,表示最后剩下了几号     

 

Sample Input

2
5 3
6 4

Sample Output

4
5
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int number;
struct node * next;
}person;//结点类型 
person * list(int n)
{
    person * head=(person*)malloc(sizeof(person));
    head->number=1;
    head->next=NULL;
    person * cyclic=head;
    for (int i=2; i<=n; i++) 
    {
        person * body=(person*)malloc(sizeof(person));
        body->number=i;
        body->next=NULL;
        cyclic->next=body;
        cyclic=cyclic->next;
    }
    cyclic->next=head;//首尾相连
    return head;
}


void find_delete(person * head,int m)//此步我是将删除和遍历写在一起的,可分开 
{
    person * tail=head;
    //找到链表第一个结点的上一个结点,为删除操作做准备
    while (tail->next!=head) 
    {
        tail=tail->next;
    }
    person * p=head;
    //找到编号为1的人
    while (p->number!=1) 
    {
        tail=p;
        p=p->next;
    }
    //从编号为1的人开始,只有符合p->next==p时,说明链表中除了p结点,所有编号都出列了,
    while (p->next!=p) 
    {
    //找到从p报数1开始,报m的人,并且还要知道数m-1的人的位置tail,方便做删除操作。
        for (int i=1; i<m; i++) 
        {
            tail=p;
            p=p->next;
        }
        tail->next=p->next;//从链表上将p结点摘下来
        free(p);
        p=tail->next;//继续使用p指针指向出列编号的下一个编号,比赛继续
    }
    printf("%d\n",p->number);
    free(p);
}


int main() 
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
    int n;
    scanf("%d",&n);
    person * head=list(n);
    int m;
    scanf("%d",&m);
    find_delete(head,m);
    }
    return 0;
}

 

 

 

 

posted @ 2019-01-01 23:24  MichaelCecil  阅读(774)  评论(0编辑  收藏  举报