[关闭]
@quinn 2015-03-20T01:27:10.000000Z 字数 666 阅读 1640

循环链表范例(约瑟夫问题)

数据结构


从N个人中选出一个领导人,方法如下:
所有人排成一个圆圈,按顺序每隔第M个人淘汰出局,然后剩下的人聚拢重新形成圆圈,找出最后剩下的那个人

参考:《算法:C语言实现》 P52

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef int elem_type;
  4. typedef struct Node node;
  5. struct Node
  6. {
  7. elem_type elem;
  8. node* next;
  9. };
  10. int main(int argc, char *argv[])
  11. {
  12. int N = atoi(argv[1]);
  13. int M = atoi(argv[2]);
  14. node* h = (node*) malloc(sizeof(h)); //head
  15. node *x = h;
  16. h->elem = 1;
  17. h->next = h;
  18. for (int i = 2; i <= N; i++)
  19. {
  20. x->next = (node*) malloc(sizeof(x));
  21. x = x->next;
  22. x->elem = i;
  23. x->next = h; //指向head,循环
  24. }
  25. //x为最末一位
  26. while (x != x->next )
  27. {
  28. for (int i = 1; i < M; i++)
  29. {
  30. x = x->next; //当i=1, x->elem=1;
  31. //当i=M-1, x->elem = M-1; 当 i = M, x为第M-1个
  32. }
  33. printf("Delete: %d\n", x->next->elem);
  34. x->next = x->next->next;
  35. }
  36. printf("The leader's NO. is %d\n", x->elem);
  37. system("pause");
  38. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注