由n个已按1,2,3,.....,n编号的人围成一圈,从编号为1的人开始按1,2,3顺序循环报数,凡报到3者出圈,最后留一个人,问其编号是多少...

/*************************************************************************
    > File Name: only_one.c
    > Author: 
    > Mail: 
    > Created Time: Thu 01 Nov 2018 09:21:50 AM CST
 ************************************************************************/

#include
#include
typedef int ElemType;
typedef struct node
{
    ElemType data;
    struct node *next;
}slink;

void list(slink *head)
{
    slink *p = head->next;
    while(p!=head)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("\n");
}

void onlyone(int n)
{
    slink *head,*p,*q;
    head = p = (slink *)malloc(sizeof(slink));
    int i,m,k;
    for(i=1;i<=n;i++)
    {
        q = (slink *)malloc(sizeof(slink));
        q->data = i;
        p->next = q;
        p = q;
    }
    p->next = head; m = 0;
    while(m1)
    {
        k = 0;
        while(k<3)
        {
            k++;
            q = p;
            p = p->next;
            if(p==head)
            {
                q = p;
                p = p->next;
            }
        }
        q->next = p->next;
        free(p);
        p = q;
        m++;
    }
    list(head);
}

int main(int argc,char **argv)
{
    int n;
    printf("please input n:\n");
    scanf("%d",&n);
    onlyone(n);
    return 0;
}

 

转载于:https://www.cnblogs.com/wzqstudy/p/10220851.html

你可能感兴趣的:(由n个已按1,2,3,.....,n编号的人围成一圈,从编号为1的人开始按1,2,3顺序循环报数,凡报到3者出圈,最后留一个人,问其编号是多少...)