1、template为小写;
2、模板编程用的不熟练,尤其是表现在模板符号格式的应用上;
3、如果参数为对象,用引用格式,并考虑是否为常引用;
#ifndef _TEST_HPP_
#define _TEST_HPP_
template<typename T>
class DLLNode
{
public:
DLLNode()
{
prev = NULL;
next = NULL;
}
DLLNode(const T &i, DLLNode* p = NULL, DLLNode* n = NULL) // 如果参数为对象,用引用,并考虑是否为常引用
{
info = i;
prev = p;
next = n;
}
T info;
DLLNode *next, *prev;
};
template<typename T>
class DLList
{
public:
DLList()
{
head = tail = NULL;
}
~DLList();
void addToDLLTail(const T&);
T deleteFromDLLTail();
private:
DLLNode<T> *head, *tail;
};
#endif
#include <iostream>
#include <assert.h>
#include "test.hpp"
using namespace std;
template<typename T>
DLList<T>::~DLList()
{
for (DLLNode<T> *tmp = head; head != NULL;)
{
tmp = head;
head = head->next;
delete tmp;
}
tail = NULL;
}
template<typename T>
void DLList<T>::addToDLLTail(const T& el)
{
if (NULL == head)
{
head = tail = new DLLNode<T>(el, NULL, NULL);
}
else
{
tail->next = new DLLNode<T>(el, tail, NULL);
tail = tail->next;
}
}
// ignore empty dll
template<typename T>
T DLList<T>::deleteFromDLLTail()
{
T e = tail->info;
if (head == tail) // only only node
{
delete tail;
tail = head = NULL;
}
else
{
tail = tail->prev;
delete tail->next;
tail->next = NULL;
}
return e;
}
int main()
{
DLList<int> list;
list.addToDLLTail(10);
list.addToDLLTail(20);
list.addToDLLTail(30);
cout << list.deleteFromDLLTail() << endl;
cout << list.deleteFromDLLTail() << endl;
cout << list.deleteFromDLLTail() << endl;
return 0;
}