Josephu问题的链表解决方案

来源:互联网 发布:毛概网络课程答案2017 编辑:程序博客网 时间:2024/06/05 02:57

typedef struct Node
{
  int index;
  struct Node *next;
}JosephuNode;

int Josephu(int n, int m)
{
  int i, j;
  JosephuNode *head, *tail;
  head = tail = (JosephuNode *)malloc(sizeof(JosephuNode));
  for (i = 1; i < n; ++i)
  {
    tail->index = i;
    tail->next = (JosephuNode *)malloc(sizeof(JosephuNode));
    tail = tail->next;
  }
  tail->index = i;
  tail->next = head;

  for (i = 1; tail != head; ++i)
  {
    for (j = 1; j < m; ++j)
    {
      tail = head;
      head = head->next;
    }
    tail->next = head->next;
    printf("
%4d个出局的人是:%4d/n", i, head->index);
    free(head);
    head = tail->next;
  }
  i = head->index;
  free(head);
  return i;
}

int main()
{
  int n, m;
  scanf("%d%d", &n, &m);
  printf("
最后胜利的是%d号!/n", Josephu(n, m));
  system("pause");
  return 0;
}

原创粉丝点击