约瑟夫问题-循环链表

来源:互联网 发布:c语言 setlocale 编辑:程序博客网 时间:2024/05/16 14:53

有M个人,其编号分别为1-M。这M个人按顺序排成一个圈(如图)。现在给定一个数N,从第一个人开始依次报数,数到N的人出列,然后又从下一个人开始又从1开始依次报数,数到N的人又出列...如此循环,直到最后一个人出列为止

input:
输入只有一行,包括2个整数M,N。之间用一个空格分开

output:
输出只有一行,包括M个整数

input:
8 5

output:
5 2 8 7 1 4 6 3

分析:简单模拟,本题也可以使用数学算法具体请参考http://blog.csdn.net/bobcowwocb/archive/2009/09/08/4532033.aspx

【参考程序】:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
    int
code;
    node
*
next;
};

int
n,m,i,j;
int main(void
)
{

    node * head,* tail,* no,*
p2;
    no
=new
node;
    no
->code=1
;
    no
->next=NULL
;
    head
=tail=no
;
    scanf(
"%d%d",&n,&m
);
   
for (i=2;i<=n;i++
)
    {

        no=new
node;
        no
->code=i
;
        no
->next=NULL
;
        tail
->next=no
;
        tail
=no
;
    }

    tail->next=head
;
   
for (i=1;i<=n-1;i++
)
    {

        j=1
;
       
while (j<=m-1
)
        {

            no=no->next
;
            j
++
;
        }

        printf("%d ",no->next->code
);
        p2
=no->next
;
        no
->next=no->next->next
;
       
delete
p2;
    }

    printf("%d/n",no->code
);
    system(
"pause"
);
   
return 0
;
}