//支持下标操作(不建议这样写,效率低!链式存储的数据结构一般不会支持数据的随机存取)
T & operator[](size_t n)
{
if(n>size-1)
{
throw range_error("range_error");
}
LNode * p = head.next;
size_t i = 0;
while(i<N) { p="p-" i++;>next;
}
return p->data;
}
//返回线性表的元素个数
size_t GetSize()
{
return size;
}
//在表首增加元素
bool push_front(T t)
{
LNode * p = head.next;
LNode * pl = new LNode();
pl->data = t;
head.next = pl;
pl->next = p;
if(pr==&head) //先判断是否为空表
{
pr = pl;
}
size++;
return true;
}
//在表尾增加元素
bool push_back(T t)
{
LNode * pl = new LNode();
pl->data = t;
if(pr==&head) //先判断是否为空表
{
head.next = pl;
pr = pl;
}
else
{
pr->next = pl;
pl->next = 0;
pr = pl;
}
size++;
return true;
}
//返回第一个元素
T & front()
{
if(pr==&head)
throw runtime_error("链表为空!");
return (head.next)->data;
}
//返回最后一个元素
T & back()
{
if(pr==&head)
throw runtime_error("链表为空!");
return pr->data;
}
//在第n个元素前插入一个元素
bool insert(T t,size_t n)
{
if(n<=0||n>size)
{
throw range_error("range_error");
}
LNode * p = &head;
size_t i = 1;
while(i<N) { p="p-" i++;>next;
}
LNode * pl = new LNode();
pl->data = t;
pl->next = p->next;
p->next = pl;
size++;
return true;
}
//删除第n个元素
bool dele(T & t,size_t n)
{
if(n<=0||n>size)
{
throw range_error("range_error");
}
LNode * p = &head;
size_t i = 1;
while(i<N) { p="p-" i++;>next;
}
LNode * pd = p->next;
t = pd->data;
p->next = p->next->next;
if(n==size)
{
pr = p;
}
size--;
delete pd;
return true;
}
//清空整个链表
bool clear()
{
LNode * pl = head.next;
while (pl)
{
/*delete pl;
pl = pl->next;*/ //说明:在C语言里可以用这种写法,但危险性极大
LNode * p2 = pl->next;
delete pl;
pl=p2;
}
size = 0;