zoukankan      html  css  js  c++  java
  • 猴子选大王

    m只猴子围坐成一个圈,按顺时针方向从1到m编号。然后从1号猴子开始沿顺时针方向从1开始报数,报到n的猴子出局,再从刚出局猴子的下一个位置重新开始报数,如此重复,直至剩下一个猴子,它就是大王。设计并编写程序,实现如下功能:
    (1)要求由用户输入开始时的猴子数m、报数的最后一个数n。
    (2)给出当选猴王的初始编号。

    代码实现:

    #include <stdio.h>
    #include <stdlib.h>
    struct Node
    {
        int data;
        struct Node *next;
    };
    
    int main()
    {
        struct Node *head, *s, *q, *t;
        int n, m, count=0, i;
        printf("input the number m:");
        scanf("%d",&m);
        printf("input the number n:");
        scanf("%d",&n);
        //=========================
        //创建循环链表
        for(i = 0; i< m;i++)
        {
            s = (struct Node *)malloc(sizeof(struct Node));
            s->data = i+1;
            s->next = NULL;
            if(i == 0)
            {
                head = s;
                q = head;
            }
            else 
            {
                q->next = s;
                q = q->next;
            }
        }
        q->next = head;
        //=========================
        printf("init:
    ");
        q = head;
        while(q->next != head)
        {
            printf("%d ",q->data);
            q = q->next;
        }
        printf("%d ",q->data);
        //=========================
        q = head;
        printf("
    out:
    ");
        do{
            count++;
            if(count == n-1)
            {
                t=q->next;
                q->next=t->next;
                printf("%d ", t->data);
                free(t);
                count=0;
            }
            q = q->next;
        }while(q->next != q);
        printf("
    the king is: %d
    ",q->data);
        free(q);
    }

    运行结果:

    input the number m:10
    input the number n:3
    init:
    1 2 3 4 5 6 7 8 9 10 
    out:
    3 6 9 2 7 1 8 5 10 
    the king is: 4
  • 相关阅读:
    CentOS安装
    java字符串
    h5弹球对战游戏
    看是否健康
    layui社区源码笔记之fly-list
    layui社区源码笔记之user-rank
    layui社区源码笔记之layui-input form
    layui社区源码笔记之fly-tab
    layui社区模板主页框架分析
    分组答辩小程序
  • 原文地址:https://www.cnblogs.com/swblog/p/3326176.html
Copyright © 2011-2022 走看看