单链表解决约瑟夫问题(C++)

#include<iostream>
using namespace std;
//typedef int Node_entry;
struct Node{
 int entry;
 Node *next;
 Node();
 //Node(Node_entry item,Node*add_on=NULL);
};
Node *creat_cirList(int n);
void Joseph(Node *head,int m);

Node::Node()
{
 next=NULL;
}

Node *creat_cirList(int n)    //构造循环链表
{
 //Node a;
 cout<<"环形链表:  ";
 Node *head=NULL,*p,*r;  //p记录每个新建的node结点,r形成链表
 for(int i=1;i<=n;i++)
 {
  p=new Node();
  p->entry=i;
  cout<<p->entry<<"   ";
  if(head==NULL)
  {
   head=p;
  }
  else
  {
   r->next=p;
  }
  r=p;
 }
 r->next=head;  //形成环
 cout<<endl;
 return head;
}

void Joseph(Node *head,int m)    //计算叫到m号的人 head(记录整个链表) 
{
 cout<<"叫到"<<m<<"的人的顺序;  ";
 Node *p,*q;
 p=head;
 while(p->next!=p)
 {
  for(int i=1;i<m;i++)
  {
   q=p;
   p=p->next;
  }
  q->next=p->next;
  cout<<p->entry<<"   ";
  delete p;
  p=q->next;
 }
 cout<<p->entry;
 cout<<endl;
}

void main()
{
 int n,m,i=1;
 cin>>n;
 cin>>m;
 Node*t=creat_cirList(n);
 Joseph(t,m); 
 system("pause");
}

 

 

 

以上代码有一个问题:当m=1(即密码为1时),会报错,现在修改如下:

void Joseph(Node *head,int m)    //计算叫到m号的人 head(记录整个链表)
{
cout
<<"叫到"<<m<<"的人的顺序;  ";
Node
*p,*q;
p
=head;
while(p->next!=p)
{
 
for(int i=1;i<m;i++)
  {
   q
=p;
   p
=p->next;
  }
  q
->next=p->next;
  cout
<<p->entry<<"   ";
  delete p;
  p
=q->next;
}
cout
<<p->entry;
cout
<<endl;
}

改为:

 

void Joseph(Node *head,int m)    //计算叫到m号的人 head(记录整个链表) 
{
	cout<<"叫到"<<m<<"的人的顺序;  ";
	Node *p,*q;
	p=head;

	while(p->next!=p)
	{
		if(m!=1)
		{	
			for(int i=1;i<m;i++)
			{
				q=p;
				p=p->next;
			}
			q->next=p->next;
			cout<<p->entry<<"   ";
			delete p;
			p=q->next;	
		}
		else{                                   //处理m=1,遍历链表到尾结点,以删除第一个结点,有点烦呀	
			while(p->entry<p->next->entry)
			{		
				p=p->next;
			}
			q=p;
			p=p->next;
			q->next=p->next;
			cout<<p->entry<<"   ";
			delete p;
			p=q->next;
		}
	}
	cout<<p->entry;
	cout<<endl;	
}

 

 

 

 

Reference:http://www.oschina.net/code/snippet_188162_9893        (C语言)

转载于:https://www.cnblogs.com/bless123/archive/2013/04/17/Joseph.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值