类模板---双向链表

来源:互联网 发布:信贷数据分析 编辑:程序博客网 时间:2024/06/06 12:53
#ifndef DOUBLY_LINKED_LIST#define DOUBLY_LINKED_LISTtemplate<class T>class DLLNode{public:DLLNode(){next = prev = 0;}DLLNode(const T& el, DLLNode *n = 0, DLLNode *p = 0){info = el; next = n; prev =p;}T info;DLLNode *next, *prev;};template<class T>class DoublyLinkedList{public:DoublyLinkedList(){head = tail = 0;}void addToDLLTail(const T&);void addToDLLHead(const T&);T deleteFromDLLTail();T print();protected:DLLNode<T> *head, *tail;};template<class T>void DoublyLinkedList<T>::addToDLLTail(const T& el){if (tail != 0){tail = new DLLNode<T>(el,0,tail);tail -> prev ->next = tail;}else head = tail = new DLLNode<T>(el);}template<class T>void DoublyLinkedList<T>::addToDLLHead(const T& el){if (head != 0){head = new DLLNode<T>(el,head,0);head -> next->prev = head;}else head = tail = new DLLNode<T>(el);}template<class T>T DoublyLinkedList<T>::deleteFromDLLTail(){T el = tail ->info;if (head == tail){delete head;head = tail = 0;}else{tail = tail ->prev;delete tail->next;tail->next=0;}return 0;}template<class T>T DoublyLinkedList<T>::print(){DLLNode<int> *tmp = head;while(0!=tmp){cout<<tmp->info<<" ,";tmp = tmp ->next;}cout<<endl;return 0;}#endif

#include <iostream>#include "genDLList.h"using namespace std;int main(){DoublyLinkedList<int> a;//模板实例化a.addToDLLTail(1);DoublyLinkedList<int> b;b.addToDLLHead(1);DoublyLinkedList<int> *list = new DoublyLinkedList<int>;list->addToDLLTail(4);list->addToDLLTail(2);list->addToDLLHead(3);list->addToDLLHead(3);list->deleteFromDLLTail();list->print();//IntSLList *list = new IntSLList();//list->addToHead(1);//list->addToHead(2);//list->addToHead(3);//list->addToTail(5);//list->print();system("pause");}

0 0