//输入功能请在调用Insert()之前,自己在main()中设置好入参
#include
#include
const double eps=1e-5;
//基类
template
class LinearList
{
public:
virtual bool IsEmpty()const=0;
virtual int Length()const=0;
virtual bool Find(int i,T &x)const=0;
virtual int Search(T x)const=0;
virtual bool Insert(int i,T x)=0;
virtual bool Delete(int i)=0;
virtual bool Update(int i,T x)=0;
virtual void Output(ostream &out)const=0;
protected:
int n; //the length
};
template
class SingleList;
//节点
template
class Node
{
private:
T element;
Node
friend class SingleList
};
//真正实现的线性链表类
template
class SingleList:public LinearList
{
public:
SingleList();
~SingleList();
bool IsEmpty()const;
int Length()const;
bool Insert(int i,T x);
bool Find(int i,T &x)const;
int Search(T x)const;
bool Delete(int i);
bool Update(int i,T x);
bool Delete(T x);
bool Reverse();
void Output(ostream &out)const;
private:
Node
};
template
SingleList
{
first=NULL;
n=0;
}
template
SingleList
{
Node
while(first)
{
p=first->link;
delete first;
first=p;
}
}
template
bool SingleList
{
return n==0;
}
template
int SingleList
{
return n;
}
//按下标查找,找到的值放入x
template
bool SingleList
{
if(i<0||i>n-1)
{
cout<<"Out Of Bounds"<
}
Node
for(int j=0;j {
p=p->link;
}
x=p->element;
return true;
}
//按值x查找,返回下标
template
int SingleList
{
Node
for(int j=0;p&&abs(x-(p->element))>eps;j++)
{
p=p->link;
}
if(p)
return j;
return -1;
}
//按下标删除
template
bool SingleList
{
if(!n)
{
cout<<"Underflow!"<
}
if(i<0||i>n-1)
{
cout<<"Out Of Bounds!"<
}
Node
for(int j=0;j
q=q->link;
}
if(i==0)
{
first=first->link;
}
else
{
p=q->link;
q->link=p->link;
}
delete p;
n--;
return true;
}
//按值x删除
template
bool SingleList
{
if(!first)
{
cout<<"Underflow!"<
}
else
{
Node
for(p=first;p!=NULL;p=p->link)
{
if(abs(x-(p->element))
first=first->link;
delete p;
n--;
return true;
}
else if(abs(x-(p->element))
Node
while(q->link!=p)
{
q=q->link;
}
q->link=p->link;
delete p;
n--;
return true;
}
}
cout<<"Not Found,delete failed!"<
}
}
//i=-1,插入到头结点;否则插入到下标为i的节点之后
template
bool SingleList
{
if(i<-1||i>n-1)
{
cout<<"Out Of Bounds!"<
}
Node
q->element=x;
Node
if(i>-1)
{
for(int j=0;j {
p=p->link;
}
q->link=p->link;
p->link=q;
}
else
{
q->link=first;
first=q;
}
n++;
return true;
}
template
bool SingleList
{
if(i<-1||i>n-1)
{
cout<<"Out Of Bounds!"<
}
Node
for(int j=0;j {
p=p->link;
}
p->element=x;
return true;
}
template
void SingleList
{
Node
while(p)
{
out<
p=p->link;
}
out<