我们互相提提意见把!我着也编了约瑟夫问题!看看呗!
#include"god.h"
void main()
{
int size,number;
cout<<"输入结点总数:";
cin>>size;
cout<<"输入取出序号:";
cin>>number;
List T1,T2;
for(int i=1;i<=size;i++)
T1.insert(i*2);
cout<<T1;
for(int j=0;j<size;j++)
T1.find(number,T2);
cout<<T2;
system("pause");
}
#include<iostream>
using namespace std;
class List;
ostream& operator<< (ostream&,List&);
class ListNode
{
int data;
ListNode* link;
friend class List;
friend ostream& operator<< (ostream&,List&); //试试成员函数???????????
};
class List
{
ListNode *head,*flag; //flag为记数起始点的标志
public:
List();
~List(){delete head;}
bool find(const int i,List&); // *****重点函数
List& insert(const int t); // ***末段插入
List& del(const int t); // ***末段删除
ListNode* hd();
friend ostream& operator<< (ostream&,List&); //试试成员函数???????????
};
//******************************
List::List()
{
ListNode* p;
p=new ListNode;
head=p;
p->link=head;
p->data=0;
}
//****************************
bool List::find(const int i,List& T)
{
ListNode *p,*q;
p=flag;
if(i<1)
{
cerr<<"查找出错!";
exit(1);
}
for(int index=1;index<i-1;index++) //for(int index=0;index<i && p->link!=head;index++)
{
if(p==head)p=p->link;
p=p->link;
}
if(p->link==head)p=p->link;
q=p->link;
flag=q->link;
p->link=q->link; //以上为连接为循环表
T.insert(q->data);
delete q; // T.del(p->data); 保留头节点head
return true;
}
//*****************************
List& List::insert(const int t)
{
ListNode *p,*q;
p=new ListNode;
p->data=t;
q=head;
while(q->link!=head)q=q->link;
q->link=p;
p->link=head; //单结点,和其它情况均成立
flag=head->link;
return *this;
}
//*****************************
List& List::del(const int t)
{
ListNode*p,*q;
p=head;
while(p!=head)
if(p->data==t)
{
q=p->link;
p->link=q->link;
delete q;
}
else
p=p->link;
return *this;
}
//****************************
ListNode* List::hd()
{
return head;
}
//****************************
ostream& operator<<(ostream& out,List& L)
{
ListNode* p;
p=L.head; //不能把链表附给接点指针????????friend 为什么不行
p=p->link;
while(p!=L.head)
{
out<<p->data<<" ";
p=p->link;
}
out<<endl;
return out;
}
//*************************