Jonsephus问题

一个关于循环链表的典型应用.

大致过程建立循环链表,输出循环链表,处理循环链表依次去掉那些节点. 程序如下:

// Jonse.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream.h"
#include "iomanip.h"

struct Jonse
 {
  int code;
  Jonse *next;
 };

Jonse *Create(int);
void ShowList(Jonse*);
void Out(Jonse*,int,int);

int main(int argc, char* argv[])
{
 Jonse *head;
 int num,val,beg;
 cout<<"/nplease input the number of total:/n";
 cin>>num;
 head=Create(num);
 ShowList(head);
 cout<<"/nplease input the code of begin:/n";
 cin>>beg;
 cout<<"/nplease input the interval of couting:/n";
 cin>>val;
    cout<<"the new list is:/n";
 Out(head,beg,val);
 return 0;
}

 Jonse *Create(int n)
{
 Jonse *h,*p;
 h=new Jonse;
 p=h;
 for(int i=1;i<=n;i++)
 {
  p->code=i;
  if(i<n)
  {
   p->next=new Jonse;
   p=p->next;
  }
 }
 p->next=h;
 return h;
}

void ShowList(Jonse *h)
{
 Jonse *p;
 p=h;
 do
 {
  cout<<p->code<<'/t';
 }while(p!=h);
}

void Out(Jonse *h,int i,int d)
{
 Jonse *p,*q;
 int k;
 p=h;
 for(q=h;q->next!=h;q=q->next)
  for(k=1;k<i;k++)
  {
   q=p;
   p=p->next;
  }
 while(p!=p->next)
 {
  for(k=1;k<d;k++)
  {
   q=p;
   p=p->next;
  }
  cout<<p->code<<'/t';
  q->next=p->next;
  delete p;
  p=NULL;
  p=q->next;
 }
 cout<<p->code<<endl;
 delete p;
 p=NULL;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值