想着挺简单的,也就是push,pop,top,size,empty等几个操作,但是真正写起来才发现,自己C++的知识忘了好多。template更是一窍不通。对着一堆错误改了好久好久才终于编译成功。分享一下自己的代码,希望对后学者有所帮助。
/**
* @file ABStack.cpp
* @Brief stack implemented by Brian
* @author Brian
* @version 1.0
* @date 2013-08-28
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory.h>
using namespace std;
template<typename T>
struct ABNode{
ABNode<T>* next;
T data;
ABNode(T v):data(v),next(NULL){}
};
template<typename T>
class ABStack{
protected:
public:
ABStack(){init();}
~ABStack();
void push (const T& val);
void pop();
T top();
bool empty();
size_t size();
void init();
private:
ABNode<T>* head;
size_t count;
};
template<typename T>
ABStack<T>:: ~ABStack(){
ABNode<T>* p = head;
while(p){
ABNode<T>* tmp = p;
p = p->next;
delete tmp;
}
}
template<typename T>
void ABStack<T>::init(){
this->head = new ABNode<T>(-1);
this->head->next = NULL;
this->count = 0;
}
template<typename T>
void ABStack<T>::push(const T& val){
ABNode<T>* node = new ABNode<T>(val);
node->next = head->next;
node->data = val;
head->next = node;
count++;
}
template<typename T>
void ABStack<T>::pop(){
if(empty())
return;
else{
ABNode<T>* tmp = head->next;
head->next = head->next->next;
delete tmp;
}
count--;
}
template<typename T>
T ABStack<T>::top(){
if(empty()){
throw "Stack is empty!";
}else{
return head->next->data;
}
}
template<typename T>
bool ABStack<T>::empty(){
return count==0;
}
template<typename T>
size_t ABStack<T>::size(){
return count;
}
int main(){
try{
ABStack<int> istack;
cout<<istack.empty()<<endl;
istack.push(1);
istack.push(2);
cout<<"size: "<<istack.size()<<endl;
cout<<"top: "<<istack.top()<<endl;
istack.pop();
cout<<"top: "<<istack.top()<<endl;
istack.pop();
cout<<istack.empty()<<endl;
}catch(const char* s){
cout<<s<<endl;
}
return 0;
}
template需要注意如果函数实现放外面的话必须前面加 classname<T>:: 上面还得重复加template<typename T>,如果不分.h和.cpp的话还不如直接在里面实现。当然,最好还是遵循接口与实现分离的原则。