约瑟夫问题—由线性链表实现

来源:互联网 发布:http index.php 编辑:程序博客网 时间:2024/06/04 23:03

问题:N个人围成一圈,从第一个开始报数,第M个将被杀掉,最后剩下一个,其余人都将被杀掉。
例如:N=6, M=5, 被杀掉的人的序号为5,4,6,2,3.最后剩下1号
 
实现代码如下:
 
#define N 3
typedef struct _node_
{
 int data;
 struct _node_ *next;
} linknode, *linklist;
int main()
{
 int i, n;
 linklist p, q;
 printf("please input the number of nodes : ");
 scanf("%d", &n);
 p = (linklist)malloc(sizeof(linknode));
 p->data = 1;
 p->next = NULL;
 q = p;
 for (i=2; i<=n; i++)
 {
  q->next = (linklist)malloc(sizeof(linknode));
  q = q->next;
  q->data = i;
 }
 q->next = p;
 while (p->next != p)
 {
  for (i=0; i<N-2; i++) p = p->next;
  q = p->next;
  p->next = q->next;
  printf("%d ", q->data);
  free(q);
  p = p->next;
 } 
 printf("%d\n", p->data);
 return 0;
}