VS2005运行通过,如有问题,请各位大牛指正。
注意:双向链表含有头结点
#include <iostream>
using namespace std;
template<class Type>
struct Node
{
Type data;
Node<Type>* prior;
Node<Type>* next;
};
template<class Type>
class DoubleList
{
protected:
int len;//链表中结点个数
Node<Type>* Head; //指向头结点
public:
DoubleList();//默认构造函数
DoubleList(const DoubleList<Type>& otherList);//拷贝构造函数
~DoubleList();
void createListForward();//头插法
void createBackward();//尾插法
void initList();//生成头结点,尾部设置为NULL
bool isEmptyList();
int length();
void destoryList();
void getFirstData(Type& firstItem);
void search(const Type searchItem);
void insertFirst(const Type newItem);
void insertLast(const Type newItem);
void insertBefore(const int pos,const Type newItem);
void insertAfter(const int pos,const Type newItem);
void deleteNode(const Type deleteItem);
void deleteNode(const int pos,Type& deleteItem);
void reverse();
const DoubleList<Type>& operator=(const DoubleList<Type>&otherList);
friend ostream& operator<< <>(ostream& cout,const DoubleList<Type>& list);//注意 在<< 后加上 <>表明这是个函数模板
};
template<class Type>
DoubleList<Type>::DoubleList() //初始化时,只有一个头结点,有head指向
{
Head = new Node<Type>;
Head->next = NULL;
len =0;
}
template<class Type>
DoubleList<Type>::DoubleList(const DoubleList<Type>&otherList)
{
//首先建立头结点
Head = new Node<Type>;
Head->next = NULL;
Head->prior = NULL;
len =0;
Node<Type>* current = Head;//总是指向本链表的最后一个结点,待插入结点直接插入
Node<Type>* otherListCurrent=otherList.Head->next;//otherListCurrent指向第一个元素
while(otherListCurrent!=NULL)//拷贝的目标不为空
{
Node<Type>* newNode = new Node<Type>;
newNode->data = otherListCurrent->data;
newNode->next = current->next;
current->next = newNode;
newNode->prior = current;
current=current->next;
otherListCurrent = otherListCurrent->next;
len++;
}
}
template<