还是约瑟夫环,改了过后能编译,但运行不了啊

来源:百度知道 编辑:UC知道 时间:2024/09/22 10:34:42
#include<iostream>
using namespace std;

template<class Elem>
class Link
{
public:
Elem element;
Link *next;
Link(const Elem& e,Link* n=head)
{
element=e;
}
Link(Link* n=0)
{
next=n;
}
};

template <class Elem>
class LList
{
Link<Elem>* head;
Link<Elem>* tail;
Link<Elem>* fence;
int leftcnt;
int rightcnt;
void init()
{
fence=tail=head=new Link<Elem>;
leftcnt=rightcnt=0;
}
void removeall()
{
while(head!=0)
{fence =head;
head=head->next;
delete fence;
}
}
public:
LList(int size=30)
{init();}
~LList()
{
removeall();
init();
}
bool insert(const Elem&);
bool append(const Elem& item)
{
tail=tail->next=new Link<Elem>

我觉得这个程序逻辑上有问题,就算修正能够正常运行结果也不正确。
有两个地方需要注意一下:
1. 构造函数内应该初始化next成员吧
Link(const Elem& e,Link* n=head)
{
element=e;
next = NULL;
}

2. 使用指针前一定要记得判断其非空,那样可以避免很多麻烦
bool getValue(Elem& it) const
{
if (rightlength()==0) return false;
if (fence && fence->next)
it=fence->next->element;
return true;
}