#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
template<class ElemType>
class linklist
{
public:
linklist(); //构造函数
~linklist(); //析构函数
bool insert(int pos, ElemType e); //在pos位置插入e
bool del(int pos, ElemType &e); //在pos位置删除元素,用e返回
bool del(int pos); //在pos位置删除元素,用e返回
bool empty() const; //判断链表是否为空
int length() const; //返回链表的长度
ElemType& operator[] (int index) throw(out_of_range);//返回index位置的值
private:
class node
{
public:
ElemType data; //数据域
node *next; //指针域
};
node *head;
};
template<class ElemType>
linklist<ElemType>::linklist()
{
head = new node();
head -> next = NULL;
}
template<class ElemType>
linklist<ElemType>::~linklist()
{
node *q;
while(head->next != NULL)
{
q = head -> next;
head -> next = q -> next;
delete q;
}
delete head;
}
template<class ElemType>
bool linklist<ElemType>::insert(int pos, ElemType e)
{
node *p;
node *q = new node;
q -> data = e;
p = head;
if(pos < 1)
return false;
for(int i = 1; i < pos; ++i)
{
if(p -> next != NULL)
p = p -> next;
else
return false;
}
q -> next = p -> next;
p -> next = q;
return true;
}
template<class ElemType>
bool linklist<ElemType>::del(int pos, ElemType &e)
{
node *p, *q;
p = head;
if(pos < 1)
return false;
for(int i = 1; i < pos; ++i)
{
if(p -> next != NULL)
p = p -> next;
else
return false;
}
if(p -> next -> next == NULL)
{
delete p -> next;
p -> next = NULL;
}
else
{
q = p -> next;
p -> next = q -> next;
delete q;
}
return true;
}
template<class ElemType>
bool linklist<ElemType>::del(int pos)
{
ElemType e;
del(pos, e);
}
template<class ElemType>
bool linklist<ElemType>::empty() const
{
return head -> next == NULL;
}
template<class ElemType>
int linklist<ElemType>::length() const
{
node *p = head;
int len = 0;
while(p -> next)
{
++len;
p = p -> next;
}
return len;
}
template<class ElemType>
ElemType& linklist<ElemType>::operator[] (int index) throw(out_of_range)
{
if (index < 1 || index > length())
{
throw out_of_range("out of range"); //超出范围跑出异常
}
node *p;
p = head;
for(int i = 0; i < index; ++i)
p = p -> next;
return p -> data;
}
int main()
{
return 0;
}
数据结构链表C++实现
最新推荐文章于 2022-06-08 11:29:58 发布