循环链表范例(约瑟夫问题) 数组实现
#include<stdio.h>
#include<math.h>
#include <stdlib.h>
#define CALLOC(P, N, S)\
if(!((P)=calloc(N, S))){\
printf( stderr, "Insufficient memory");\
exit(EXIT_FAILURE);\
}
int main(void)
{
int N,M;
short *item,*next,*P1,*P2;
printf("输入人数N\n");
printf("输入N的底数:");
scanf("%d", &N);
getchar();
printf("输入N的指数:");
scanf("%d", &M);
getchar();
N=pow(N,M);
printf("输入间隔M:");
scanf("%d", &M);
getchar();
CALLOC(item, N, sizeof(short));
P1=item;
CALLOC(next, N, sizeof(short));
P2=next;
//分配空间给next&item
for(short i=0,k=1,g=N-1; i<g; i++,k++)
{
item[i]=k;
next[i]=k;
}
item[N-1]=N;
next[N-1]=0;
short X=N-1;
//初始化next&item&X
while(X!=next[X])
{
for(short i=1; i<M; i++)
X=next[X];
next[X]=next[next[X]];
//循环M-1次后将第M个元素移除
//X指向下一个元素
}
printf("%d\n",item[next[X]]);
free(P1);
free(P2);
//释放next&item
return 0;
}
posted on 2018-02-14 11:00 MACHINE_001 阅读(110) 评论(0) 编辑 收藏 举报