编一个程序,实现单链表的基本操作,包括链表的建立、释放、查找、插入、删除等函数,要求同时具备输入输

急急急急急急急急!高手赐教,要正确的额啊
2024-11-13 04:07:19
推荐回答(1个)
回答1:

//输入功能请在调用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 *link;
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 *first;
};

template
SingleList::SingleList()
{
first=NULL;
n=0;
}

template
SingleList::~SingleList()
{
Node *p;
while(first)
{
p=first->link;
delete first;
first=p;
}
}

template
bool SingleList::IsEmpty()const
{
return n==0;
}

template
int SingleList::Length()const
{
return n;
}

//按下标查找,找到的值放入x
template
bool SingleList::Find(int i,T &x)const
{
if(i<0||i>n-1)
{
cout<<"Out Of Bounds"< return false;
}
Node *p=first;
for(int j=0;j {
p=p->link;
}
x=p->element;
return true;
}

//按值x查找,返回下标
template
int SingleList::Search(T x)const
{
Node *p=first;
for(int j=0;p&&abs(x-(p->element))>eps;j++)
{
p=p->link;
}
if(p)
return j;
return -1;
}

//按下标删除
template
bool SingleList::Delete(int i)
{
if(!n)
{
cout<<"Underflow!"< return false;
}
if(i<0||i>n-1)
{
cout<<"Out Of Bounds!"< return false;
}
Node *p=first, *q=first;
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::Delete(T x)
{
if(!first)
{
cout<<"Underflow!"< return false;
}
else
{
Node *p;

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 *q=first;
while(q->link!=p)
{
q=q->link;
}
q->link=p->link;
delete p;
n--;
return true;
}
}
cout<<"Not Found,delete failed!"< return false;
}
}

//i=-1,插入到头结点;否则插入到下标为i的节点之后
template
bool SingleList::Insert(int i,T x)
{
if(i<-1||i>n-1)
{
cout<<"Out Of Bounds!"< return false;
}
Node *q=new Node;
q->element=x;
Node *p=first;

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::Update(int i,T x)
{
if(i<-1||i>n-1)
{
cout<<"Out Of Bounds!"< return false;
}
Node *p=first;
for(int j=0;j {
p=p->link;
}
p->element=x;
return true;
}

template
void SingleList::Output(ostream &out)const
{
Node *p=first;
while(p)
{
out<element<<" ";
p=p->link;
}
out<}