7-4 who is the last?

题目之外:

本篇旨在介绍一种非结构体的链表实现方法,该方法借助数组,可以简单实现储存值为连续整数的链表。具体实现思想为:

定义一个数组A[N],其中index表示存储的值,A[index]为下一个节点的index

题干:

There are N people, numbered from 1 to N, sitting around in a circle. Counted from the NO.1, the M th people should leave the game. Then, from the next one, the counting loop will go on. After several loops, there will be only on guy left. Writing a program to calculate who is the last people.

输入格式:

Two integers, separated by commas. The first integer represents N individuals (0<N), the second integer represents M (0<M<=N).

输出格式:

N integers, separated by commas. These numbers indicate the order of the person to leave the circle, with their numbers.

输入样例:

在这里给出一组输入。例如:

5,1

输出样例:

在这里给出相应的输出。例如:

2,4,1,5,3

 C语言代码:

#include<stdio.h>
#include<stdlib.h>

main(){
    int M,N;
    scanf("%d,%d",&N,&M);
    int i;
    //create circle
    int circle[N];
    for(i=0;i<N-1;i++) circle[i]=i+1;
    circle[N-1]=0;
    //delete
    int startPos=0,pre=-1;
    for(i=0;i<N-1;i++){
        int count=0;
        for(;count<M;count++){
            pre=startPos;
            startPos=circle[startPos];
        }
        printf("%d,",startPos+1);
        //delete curpos
        circle[pre]=circle[startPos];
        startPos=circle[startPos];
    }
    printf("%d\n",startPos+1);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值