约瑟夫环(猴子选大王)7-4 约瑟夫环

N个人围成一圈顺序编号,从1号开始按1、2、3…顺序报数,报p者退出圈外,其余的人再从1、2、3开始报数,报p的人再退出圈外,以此类推。
请按退出顺序输出每个退出人的原序号。

  • 输出格式:
    输入只有一行,包括一个整数N(1<=N<=3000)及一个整数p(1<=p<=5000)。
  • 输出格式:
    在这里给出一组输入。例如:
7 3
  • 输出样例:
3 6 2 7 5 1 4

答案:

#include <stdio.h>
#include <stdlib.h>
struct node{
    int data;
    struct node *next; 
};
int main(){
    struct node *head = NULL,*tail = NULL,*p = NULL,*q = NULL;
    int a,b;
    int i = 0;
    head = (struct node *)malloc(sizeof(struct node));
    head->data = -1;
    head->next = NULL;
    tail = head;
    scanf("%d%d",&a,&b);
    for(i = 0;i < a;i++){
        p = (struct node *)malloc(sizeof(struct node));
        p->data = i+1;
        tail->next = p;
        p->next = head->next;
        tail = p;
    }
    p = head->next;
    q = tail;
    i = 1;
    while(p!=q){
        if(i == b){
            printf("%d ",p->data);
            q->next = p->next;
            free(p);
            p=q->next;//p被删除后,需要重新定义p,所以让p指向q的next域; 
            i = 1;
        }
        else{
            q = p;
            p = p->next;
            i++;
        }
    }
    printf("%d",p->data);
    free(head);
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值