自己实现简单链表: 设计诸多不当,仅仅学习模板和异常而已,如有错误,请高手指出:
#ifndef MYLIST_H
#define MYLIST_H
//如果你用的编译器不支持C++11就取消下面的那句注释
//#define NULL nullptr
#include
//要抛出的异常
class mylistZeroSize{};//链表为空,也就是节点为0
class mylistMaxSize{};//要访问的数超过最大节点数
template
struct pNode //节点数据类型
{
T node;
struct pNode * next;
};
template
class mylist
{
public:
mylist();
~mylist();
mylist(const T node);
mylist(const mylist & temp);
void addNode(T node);//添加节点
void showNode();//输出节点
bool isNull()const;//判断是否为空
T at(int i)const;//返回某个位置的值
int size()const;//节点个数
void clear();//清空链表
const mylist operator=(const mylist & temp); //重载=号
T operator[](int i)const; //重载[]
private:
pNode * pFist;
pNode * pLast;
};
using namespace std;
template
mylist::mylist(T node)
{
pLast = new pNode;
pFist = pLast;
pLast = new pNode;
pLast->node = node;
pLast->next = nullptr;
pFist->next = pLast;
}
template
mylist::mylist()
{
pLast = new pNode;
pFist = pLast;
pLast->next = nullptr;
}
template
mylist::mylist(const mylist &temp)
{
pFist = new pNode;
pLast = pFist;
pNode * tp;
for(int i = 0; i<temp.size(); ++i)
{
tp = pLast;
pLast = new pNode;
pLast->node = temp.at(i);
pLast->next = nullptr;
tp->next = pLast;
}
}
template
mylist::~mylist()
{
this->clear();
delete pFist;
pFist = nullptr;
pLast = pFist;
}
template
void mylist::addNode(T node)
{
pNode * tp = pLast;
pLast = new pNode;
pLast->node = node;
pLast->next = nullptr;
tp->next = pLast;
return;
}
template
void mylist::showNode()
{
if (this->isNull())
{
cout << "链表为空" <<endl;
return;
}
for (int i=0; isize();++i)
{
cout <at(i) <<" ";
}
}
template
T mylist::at(int i) const
{
if(this->isNull())
{
throw mylistZeroSize();//抛出链表为空的异常
}
else
{
int j = 0;
pNode * tp = pFist->next;
do
{
if (j == i)
{
return tp->node;
}
else
{
j++;
tp = tp->next;
}
}while(tp != pLast->next);
throw mylistMaxSize();//抛出超过最大值的异常
}
}
template
const mylist mylist::operator =(const mylist & temp)
{
if (temp.isNull())
{
this->clear();
}
else
{
for (int i = 0;iaddNode(temp.at(i));
}
}
return *this;
}
template
bool mylist::isNull() const
{
if(pLast == pFist)
{
return true;
}
else
{
return false;
}
}
template
int mylist::size() const
{
if(this->isNull())
{
return 0;
}
else
{
int j = 0;
pNode * tp = pFist->next;
do
{
j++;
tp = tp->next;
}while(tp != pLast->next);
return j;
}
}
template
void mylist::clear()
{
if (this->isNull())
{
return ;
}
else
{
pNode * tp = pFist->next;
pLast = pFist;
pLast->next = nullptr;
do
{
pNode * tmp = tp;
tp = tp->next;
delete tmp;
}while (tp != pLast->next);
}
}
template
T mylist::operator[](int i)const
{
return this->at(i);
}
#endif // MYLIST_H
评论已关闭。