单链表解决约瑟夫问题(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语言)

posted @ 2013-04-17 10:29  《一直在路上~》  阅读(329)  评论(0编辑  收藏  举报