泛型编程实现双向链表

来源:互联网 发布:湖北金融数据网 编辑:程序博客网 时间:2024/05/01 13:15
#ifndef _DULLIST_H_
#define _DULLIST_H_
#include <iostream>
using namespace std;
template<typename T>
class Node
{
public:
T data;
Node *next;
Node *prior;
};


template<typename T>
class DulList
{
public:
DulList();
~DulList();
void Clear();
bool IsEmpty();
int Length(); 
bool GetElementByPos(int pos, T &e);
bool InsertElementByPos(int pos,const T &e);
bool DeleteElementByPos(int pos, T &e);
void PrintFirst();
void PrintLast();
private:
Node<T> *head;
};
#endif


template<typename T>
DulList<T>::DulList()
{
head = new Node<T>();
head->next = head->prior = head;
}


template<typename T>
DulList<T>::~DulList()
{
Node<T>* temp = nullptr;
Node<T>* index = head->next;
while (index != head)
{
temp = index->next;
delete index;
index = temp;
}
delete head;
head = nullptr;
}


template<typename T>
void DulList<T>::Clear()
{
Node<T>* temp = nullptr;
Node<T>* index = head->next;
while (index != head)
{
temp = index->next;
delete index;
index = temp;
}
head->next = head->prior = head;
}


template<typename T>
bool DulList<T>::IsEmpty()
{
return head->next == head && head->prior == head;
}


template<typename T>
int DulList<T>::Length()
{
Node<T>* index = head->next;
int Length = 0;
while (index != head)
{
index = index->next;
++Length;

}
return Length;
}




template<typename T>
bool DulList<T>::GetElementByPos(int pos, T &e)
{
Node<T>* index = head;
int Length = 0;
while (index->next != head)
{
++Length;
if (Length == pos)
{
e = index->next->data;
return true;
}
index = index->next;
}
return false;
}


template<typename T>
bool DulList<T>::InsertElementByPos(int pos, const T &e)
{
Node<T>* index = head;
int Length = 0;
while (index->next != head || index->next == head  && Length == pos - 1)
{
if (Length == pos-1)
{
Node<T>* temp = new Node<T>();
temp->data = e;
temp->next = index->next;
temp->next->prior = temp;
temp->prior = index;
index->next = temp;
return true;
}
index = index->next;
++Length;

}
return false;
}


template<typename T>
bool DulList<T>::DeleteElementByPos(int pos, T &e)
{
Node<T>* index = head;
int Length = 0;
while (index->next != head)
{
if (Length == pos)
{
Node<T>* temp = index;
e = temp->data;
index->prior->next = index->next;
index->next->prior = index->prior;
delete temp;
return true;
}
index = index->next;
++Length;

}
return false;
}


template<typename T>
void DulList<T>::PrintFirst()
{


Node<T>* index = head->next;
while (index != head)
{
cout << index->data << " ";
index = index->next;
}
cout << endl;
}




template<typename T>
void DulList<T>::PrintLast()
{


Node<T>* index = head->prior;
while (index != head)
{
cout << index->data << " ";
index = index->prior;
}
cout << endl;
}
0 0