标题:约瑟夫问题
只看楼主
zhuxu0423
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:59
专家分:101
注 册:2010-4-12
得分:2 
扩展为:从1至N开始顺序循环数数,每数到M输出该数值,直至全部输出
链表实现:
#include <stdio.h>
#include <malloc.h>
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;
}
2010-06-02 13:32



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-308710-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019119 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved