josephus 约瑟夫的循环链表实现

//有n个人围坐在一个圆桌周围,现从第s个人开始报数,数到第m
//的人出列,然后从出列的下一个人重新开始报数,数到第m的人
//又出列,…,如此反复直到所有的人全部出列为止。

#include <iostream>
#include <iomanip>
using namespace std;

typedef struct LNode{
 int NO;
 struct LNode * next;
}Lnode, *Josephus;

Josephus InitJosephus()
{
 LNode * head = new LNode;
 head->next = head;
 head->NO = 0;
 return head;
}

Josephus CreateJosephus(int enjoyIn)
{
 LNode * node = NULL;
    LNode * head = InitJosephus();
 LNode * forword = head;

 for( int i = 1; i <= enjoyIn; i++ )
 {
  node = new LNode;
  node->NO = i;
        forword->next = node;
  forword = forword->next;
  node->next = NULL;
 }
 forword->next = head->next;
    return head;
}

void JoseProcess( Josephus &Jose, int position, int cycle)
{
 Josephus p = Jose->next;
 Josephus qTemp = NULL;
 int temp;
 for(int i = 0; i < position-1; i++ )
 {
  p = p->next;
 }
 cout<<"Out of the queue... "<<endl;

 if(cycle == 1 && p->next != p)
 {
     qTemp = p;
  while( qTemp->next != p )
  qTemp = qTemp->next;
 }
 if(cycle == 1 && p->next == p)
 {
  cout<<"The winner is "<< p->NO <<" child! "<<endl;

 }
 while( p->next != p )
 {
  
  for(int j = 1; j < cycle; j++ )
  {
   qTemp = p;
   p = p->next;
  }

  temp = p->NO;

        qTemp->next = p->next;
  delete p;
  p = qTemp->next;
  cout<<temp<<endl;
 }
 cout<<"The winner is "<< p->NO <<" child! "<<endl;
}

void main()
{
 int enjoyIn;
 int position;
 int cycle;

 cout<<"the total of the children : ";
 cin>>enjoyIn;
 cout<<endl<<"the position you want to access : ";
 cin>>position;
 cout<<endl<<"the cycle you want : ";
 cin>>cycle;
 cout<<endl;

 Josephus Jose = CreateJosephus( enjoyIn );
    JoseProcess( Jose, position, cycle);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值