代码改变世界

约瑟夫环问题

2009-10-09 20:07  Iron  阅读(216)  评论(0编辑  收藏  举报

用户输入M,N值,从1至N开始顺序循环数数,每数到M输出该数值,直至全部输出。写出C程序。

采用循环列表,先将所有的节点加载进来,而后每数到一个,输出数据后,删除数据

#include <iostream>
#include <vector>
using namespace std;
class Node
{
public:
 Node *pre;
 Node *next;
 int data;
 Node(int d)
 {
  this->data = d;
  this->pre = NULL;
  this->next = NULL;
 }
};
class List
{
public:
 Node * head;
 Node * last;
 List()
 {
  head = last = NULL;
 }
 //插入节点
 void Add(Node * newNode)
 {
  //如果为空树
  if (NULL == head)
  {
   head = newNode;
   last = newNode;
   head->pre = last;
   head->next = last;
  }
  else
  {
   last->next = newNode;
   newNode->pre = last;
   newNode->next = head;
   last = newNode;
   head->pre = newNode;
  }
 }
 //约瑟夫函数
 void yue(int m)
 {
  int temp=1;
  Node * p = this->head;
  while(true)
  {
   if (temp == m)
   {
    Node* tempNode = p;
    cout << p->data << endl;
    //如果当前只有一个节点
    if (p->pre == p)
    {
     head = NULL;
     last = NULL;
    }
    else
    {
     p->pre->next = p->next;
     p->next->pre = p->pre;
     if (p==head)
     {
      head = p->next;
     }
     if (p==last)
     {
      last = last->pre;
     }
     p = p->next;
    }
    delete tempNode;
    temp = 1;//复位
   }
   else
   {
    //往下走
    p = p->next;
    temp++;
   }
   //如果为空链表则跳出循环
   if (head == NULL)
   {
    break;
   }
  }
 }
};
int main()
{
 int m,n;
 //scanf("%d %d",&m,&n);
 cin>>m>>n;
 List list;
 for (int i=1; i<n+1; i++)
 {
  //Node* newNode = new Node(i);
  list.Add(new Node(i));
 }
 list.yue(m);
}