#ifndef MYSTACK_H
#define MYSTACK_H
template
class MyStack
{
public:
MyStack(int size); //分配内存,初始化栈空间,设定栈容量,栈顶
~MyStack(); //回收栈空间内存
bool stackEmpty(); //判定栈是否为空,为空返回true,非空返回false。
bool stackFull(); //判断栈是否已满,已满返回true,不满返回false。
void cleanStack(); //清空栈
int stackLenth(); //已有元素的个数
bool push(T elem); //元素入栈,栈顶上升
bool pop(T &elem); //元素出栈,栈顶下降
void stackTraverse(bool isFromButtom); //遍历栈中所有元素
private:
T *m_pBuffer; //栈空间指针
int m_iSize; //栈容量
int m_iTop; //栈顶,栈中元素个数
};
template
MyStack::MyStack(int size){
m_iSize=size;
m_pBuffer=new T[m_iSize];
m_iTop=0;
}
template
MyStack::~MyStack()
{
delete[] m_pBuffer;
m_pBuffer=NULL;
}
template
bool MyStack::stackEmpty()
{
if(m_iTop==0)
{
return true;
}
return false;
}
template
bool MyStack::stackFull()
{
if(m_iTop==m_iSize)
{
return true;
}
return false;
}
template
void MyStack::cleanStack()
{
m_iTop=0;
}
template
int MyStack::stackLenth()
{
return m_iTop;
}
template
bool MyStack::push(T elem)
{
if(stackFull()){ //如果不满,就入栈
return false;
}
m_pBuffer[m_iTop]=elem;
m_iTop++;
return true;
}
template
bool MyStack::pop(T &elem)
{
if(stackEmpty()){ //如果不为空就出栈
return false;
}
//由于栈顶指针始终指向的栈顶的上面一个元素,
//也就是说是一个空元素,所以说要先执行--
//操作,然后才能获取到栈顶元素,否则会报
//空指针异常。
m_iTop--;
elem=m_pBuffer[m_iTop];
return true;
}
template
void MyStack::stackTraverse(bool isFromButtom)
{
if(isFromButtom)
{
for(int i=0;i=0;i--)
{
cout<
using namespace std;
class Coordinate
{
friend ostream &operator<<(ostream &out,Coordinate &coor);
public:
Coordinate(int x=0,int y=0);
void printCoordinate();
private:
int m_iX;
int m_iY;
};
#endif#include"Coordinate.h"
#include
using namespace std;
Coordinate::Coordinate(int x,int y)
{
m_iX=x;
m_iY=y;
}
void Coordinate::printCoordinate()
{
cout<<"("<
#include
#include"MyStack.h"
#include"Coordinate.h"
using namespace std;
int main(void)
{
MyStack *pStack=new MyStack(5);
pStack->push(Coordinate(1,2)); //栈底
pStack->push(Coordinate(3,4)); //栈顶
pStack->stackTraverse(true);
pStack->stackTraverse(false);
cout<stackLenth()<stackEmpty())
{
cout<<"栈为空"<stackFull())
{
cout<<"栈为满"<
以上内容来源于慕课网。