stack.h
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
template <class T>
struct Node{
T data;
struct Node *next;
};
template <class T>
class Stack{
public:
Stack<T>(){
head = new Node<T>;
head->next = NULL;
}
~Stack<T>(){
Destory();
}
bool push(T data);
T pop();
void Destory();
void Clear();
bool isEmpty();
private:
Node<T> *head;
};
template <class T>
bool Stack<T>::push(T data){
Node<T> *newPt = new Node<T>;
if(!newPt)
return false;
newPt->data = data;
newPt->next = head->next;
head->next = newPt;
return true;
}
template <class T>
T Stack<T>::pop(){
T data;
Node<T> *pf;
pf = head->next;
if(!pf)
return 0;
data = pf->data;
head->next = head->next->next;
delete pf;
return data;
}
template <class T>
bool Stack<T>::isEmpty(){
if(head->next)
return true;
return false;
}
template <class T>
void Stack<T>::Clear(){
while(isEmpty()){
pop();
}
}
template <class T>
void Stack<T>::Destory(){
Clear();
delete head;
}
#endif
TestStack.cpp
#include <iostream>
using namespace std;
#include "stacks.h"
int main(){
Stack<int> s;
for(int i = 0; i < 8; ++i){
s.push(i);
}
for(int i = 0; i < 8; ++i){
cout << s.pop() << " ";
}
return 0;
}