基类:
/*
*FileName: Stack.h
*Creater: QianChenglong
*Date: 2011/10/22
*Comments: the abstract base class of stack
*/
#ifndef STACK_H
#define STACK_H
template<typename T>
class Stack
{
public:
Stack() {}
~Stack() {}
virtual bool push(const T& elem) =0;
virtual bool pop(T& elem) =0;
virtual T pop() =0;
virtual bool getTop(T& elem) const=0;
virtual T getTop() const=0;
virtual int length() const=0;
virtual bool isEmpty() const=0;
virtual void outPut() const=0;
};
#endif
类定义:
#ifndef SEQSTACK_H
#define SEQSTACK_H
#include"Stack.h"
#define DEFAULT_SIZE 50
#define INCREAMENT_SIZE 20
template<typename T>
class SeqStack:public Stack<T>
{
private:
T* data;//数组指针
int top;//栈顶指针
int maxSize;//栈的最大容量
void overflowProcess();
public:
SeqStack();
~SeqStack();
bool push(const T& elem);
bool pop(T& elem);
T pop();
bool getTop(T& elem) const;
T getTop() const;
int length() const;
bool isEmpty() const;
void outPut() const;
//拓展操作
bool isFull() const;
int size() const;
};
#include"SeqStack.cpp"
#endif
类实现:
#ifndef SEQSTACK_CPP
#define SEQSTACK_CPP
#include<iostream>
#include"SeqStack.h"
template<typename T>
SeqStack<T>::SeqStack()
{
maxSize=DEFAULT_SIZE;
data=new T[DEFAULT_SIZE];
top=-1;
}
template<typename T>
SeqStack<T>::~SeqStack()
{
delete [] data;//返回data所指向的内存,因为data所指向的内存区域做过标记,可以删除那一片new过来的内存;
}
template<typename T>
void SeqStack<T>::overflowProcess()
{
maxSize+=INCREAMENT_SIZE;
T* t=new T[maxSize];
for(int i=0;i!=top+1;++i)
t[i]=data[i];
delete [] data;
data=t;
}
template<typename T>
bool SeqStack<T>::push(const T& elem)
{
if(isFull())
overflowProcess();
data[++top]=elem;
return 1;
}
template<typename T>
bool SeqStack<T>::pop(T& elem)
{
if(top==-1)
return 0;
elem=data[top--];
return 1;
}
template<typename T>
T SeqStack<T>::pop()
{
if(top==-1)
return 0;
return data[top--];
}
template<typename T>
bool SeqStack<T>::getTop(T& elem)const
{
if(top==-1)
return 0;
elem=data[top];
return 1;
}
template<typename T>
T SeqStack<T>::getTop() const
{
if(top==-1)
return 0;
return data[top];
}
template<typename T>
bool SeqStack<T>::isEmpty() const
{
return top==-1;
}
template<typename T>
int SeqStack<T>::length() const
{
return top+1;
}
template<typename T>
void SeqStack<T>::outPut() const
{
for(int i=0;i!=top+1;++i)
std::cout<<data[i]<<' ';
std::cout<<std::endl;
}
template<typename T>
bool SeqStack<T>::isFull() const
{
return top+1==maxSize;
}
template<typename T>
int SeqStack<T>::size() const
{
return maxSize;
}
#endif
功能测试:
#include<iostream>
#include"SeqStack.h"
int main()
{
SeqStack<int> Sa;
std::cout<<Sa.size()<<std::endl;
int elem;
while(std::cin>>elem)
Sa.push(elem);
std::cin.clear();
std::cout<<Sa.size()<<std::endl;
Sa.outPut();
Sa.getTop(elem);
std::cout<<elem<<std::endl;
int size=Sa.length();
for(int i=0;i!=size;++i)
{
Sa.pop(elem);
std::cout<<elem<<' ';
}
std::cout<<std::endl;
return 0;
}