#include <iostream>
#include <cstdlib>
using namespace std;
//用struct定义LinkNode类.使用这种方法使该类失去封装性,但简化了描述.
//在Link类中把first封装在了其内部,属于该Link的所有LinkNode实例都成为Link实例的私有成员,保证不被外界直接访问.
//结点模板的定义
template<typename Type>
struct LinkNode
{
Type data;
LinkNode<Type>* next;
LinkNode(const Type& item, LinkNode<Type>* ptr=NULL)//用于初始化data和next
{
data = item;
next = ptr;
}
/* LinkNode(LinkNode<Type>* ptr=NULL)
{
next = ptr;
}
*/
};
//单链表模板的定义
template<typename Type>
class List
{
private:
LinkNode<Type>* first;//链表头指针
public:
List()//构造函数
{
first = NULL;
}
List(const List<Type>& L)//拷贝构造函数
{
first = NULL;
CopyList(L);
}
List<Type>operator=(const List<Type>& L)//赋值运算符符号
{
if(this==&L)
return *this;
MakeEmpty();
CopyList(L);
return *this;
}
~List()//析构函数
{
LinkNode<Type>* p;
while(p)
{
p=first;
first=p->next;
delete p;
}
}
//单链表的增删查改
void InputFront(const Type& elem);
void InputRear(const Type& elem);
bool Insert(int i, const Type& x);
bool Remove(int i, Type& x);
//LinkNode<Type>* Search(const Type& x);
bool Search(const Type& x);
LinkNode<Type>* Locate(int i);
bool GetData(int i, Type& x)const;
bool SetData(int i, const Type& x);
//清空复制列表结点
void MakeEmpty();
void CopyList(const List<Type>& L);
//链表自身状态
int Length() const
{
LinkNode<Type>* s=first;
int count=1;
while(s->next)
{
count++;
s = s->next;
}
return count;
}
bool IsEmpty() const
{
return first==NULL;
}
bool IsFull() const
{
return false;
}
//当前指针所指向结点在链表中的位置
int GetLocation(const LinkNode<Type>* iter)
{
LinkNode<Type>* p = first;
int L = Length();
int count = 0;
while(count <= L)
{
count++;
if(p==iter)
{
return co
[数据结构]链表的实现(c++/类模板)
最新推荐文章于 2024-05-15 08:33:51 发布