template <class T>
class ChainNode {
friend Chain<T>;
private:
T data;
ChainNode<T> *link;
};
template<class T>
class Chain {
public:
Chain(){first = 0};
~Chain();
bool IsEmpty() const { return first == 0; }
int Length()const;
bool Find(int k, T &x)const;
int Search(const T& x)const;
Chain<T>& Delete(int k,T& x);
Chain<T>& Insert(int k, const T& x);
void Output(ostream& out)const;
private:
ChainNode<T> *first;//point to the first node
};
能用const的地方尽量使用const。
1.删除链表中所有结点的析构函数~Chain()
template<class T>
Chain<T>::~Chain()
{
ChainNode<T> *next;
while (first) {
next = first->link;
delete first;
first = next;
}
}
2.计算链表长度的函数Length()
template<class T>
int Chain<T>::Length()const {
int count = 0;
ChainNode<T> *current = first;
while (current)
{
count++;
current = current->link;
}
return count;
}
3.判断某个元素是否在链表中:Find()
template<class T>
bool Chain<T>::Find(int k, T& x)const {
ChainNode<T> *current = first;
int i = 0;
while (i < k && current)
{
current = current->link;
i++;
}
if (current->data == x)//这个地方和书上写法不一样
//感觉原书写错了~~
return true;
else
return false;
}
4.寻找链表中是否包含某个元素x,并返回该元素的索引。
template<class T>
int Search(const T& x)
{
ChainNode<T> *current = first;
int i = 0;
while (current->data != x && current)
{
current = current->link;
i++;
}
if(current)
return i;
else return 0;
}
5.输出函数Output():
template<class T>
void Chain<T>::Output(ostream& out)const
{
ChainNode<T> *current;
for (current = first; current; current = current->link)
out << current->data << " ";
}
6.重载<<操作符:
template<class T>
ostream& operator<<(ostream& out,const Chain<T>& x)
{
x.Output(out);
return out;
}
7.删除某个元素x:
template<class T>
Chain<T>& Chain<T>::Delete(int k, T& x) {
if (k < 1 || !first)
throw "OutOfBounds";
ChainNode<T> *current = first;
if (k == 1)
first = first->link;
else
{
ChainNode<T> *q = first;
for (int index = 1; index < k-1 && q; index++)
{
q = q->link;
}
if (!q || !q->link)
throw "OutOfBounds";
current = q->link;
q->link = current->link;
}
x = current->data;
delete current;
return *this;
}
8.插入某个元素,与删除某个元素很类似:
template<class T>
Chain<T>& Chain<T>::Insert(int k, const T& x)
{
if (k < 0)throw "OutOfBounds";
ChainNode<T> *current = first;
for(int index = 1;index<k && current;index++)
{
current = current->link;
}
if (k > 0 && !p)throw "OutOfBounds";//不存在第k个元素
ChainNode<T> *y = new ChainNode<T>;
y->data;
if (k)
{
y->link = current->link;
current->link = y;
}
else//k=0,结点y作为第一个元素插入
{
y->link = first;
first = y;
}
return *this;
}