约瑟夫问题

约瑟夫问题

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem 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>


struct node
{
    int data;


    struct node *next;
}*head;


struct node *creat(int n)
{
    struct node *p, *tail;
    int i;


    p = (struct node *)malloc(sizeof(struct node));
    p-> data = 1;
    head = p;   //去掉头结点
    tail = p;


    for(i = 2; i <= n; i++)
    {
        p = (struct node *)malloc(sizeof(struct node));
        p-> data = i;
        p-> next = NULL;
        tail-> next = p;
        tail = p;
    }


    tail-> next = head; //构成循环链表
    return head;


}


void kill(struct node *head, int m, int n)
{
    int count = 0, a = 0;
    struct node *p, *q;


    q = head;


   while(q-> next != head)
   {
     q = q-> next; // 使指针q指向尾结点
   }
    while(count < n - 1)
    {
        p = q-> next;
        a++;
         if(a % m == 0)  //前面a已经自加
        {
            q-> next = p-> next;
            free(p);
            count++;
         }


        else
        {
            q = p;  //q为了一直在p的前面
        }
    }


    printf("%d\n", q-> data);
}


int main(void)
{
    int m, n;
    struct node *h;


    scanf("%d %d", &n, &m);
    h = creat(n);


    kill(h, m, n);


    return 0;
}


*/
 
 
法二!!
#include<stdio.h>
#include<stdlib.h>


struct node
{
    int data;


    struct node *next;
}*head;


void creat(int n)
{
    int i;
    struct node *p, *tail;


    p = (struct node *)malloc(sizeof(struct node));
    p-> data = 1;
    p-> next = NULL;
    head = p;
    tail = head;


    for(i = 2; i <= n; i++)
    {
        p = (struct node *)malloc(sizeof(struct node));


        p-> data = i;
        p-> next = NULL;
        tail-> next = p;
        tail = p;
    }


    tail-> next = head;
}


void kill(int n, int m)
{
    int count = 0, num = 0;
    struct node *p, *q;


    q = head;


    while(q-> next != head)   //此时尾结点指向了head,而不是NULL
    {
        q = q-> next;
    }
   // p = head;
    while(count < n - 1)
    {
       num++;
       p = q-> next;
       if(num % m == 0)
       {
           q-> next = p-> next;
           free(p); //一定要释放不用的空间
           count++;
       }     //~~~


       else
       {
           q = p;


          // q = q-> next;   不可以利用这//三句话来写 因为p每次都会被释放,所以p = p-> next, 毫无意义。
          // p = p-> next;


       }


    }


    printf("%d\n", q-> data); //因为最终 一定是进入~~~从而结束的此时p还是毫无意义的
}


int main(void)
{
    int m, n;


    scanf("%d %d", &n, &m);


    creat(n);
    kill(n, m);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值