Josephus problem

来源:互联网 发布:限制软件联网 编辑:程序博客网 时间:2024/05/17 23:49
#include <stdlib.h>
#include <stdio.h>
struct node{
    int item;
    struct node * next;
};
typedef struct node * link;
int main(int argc, char **argv)
{
    if(!argv[1] || !argv[2])
    {
        printf("please input your two number\n");
        return -1;
    }
    int N = atoi(argv[1]);
    int M = atoi(argv[2]);
    link x , t = (link)malloc(sizeof(struct node));
    x = t;
    t->item = 1;
    t->next = t;
    
    int i ;
    link p = NULL;
    for( i = 2; i <= N ; i++)
    {
        x->next = (link)malloc(sizeof(struct node));
        x = x->next;
        x->next = t;
        x->item = i;
    }

    while(t->next != t)
    {
        for(i = 1 ; i < M; i++)
            t = t->next;
        printf("%d\n",t->next->item);
        t->next = t->next->next;        
    }
    
    printf("%d\n",t->item);
    return 0;
}
    
   
0 0
原创粉丝点击