#ifndef MYSTACK_H
#define MYSTACK_H
#include"Coordinate.h"
class MyStack
{
public:
MyStack(int size); //分配内存,初始化栈空间,设定栈容量,栈顶
~MyStack(); //回收栈空间内存
bool stackEmpty(); //判定栈是否为空,为空返回true,非空返回false。
bool stackFull(); //判断栈是否已满,已满返回true,不满返回false。
void cleanStack(); //清空栈
int stackLenth(); //已有元素的个数
bool push(Coordinate elem); //元素入栈,栈顶上升
bool pop(Coordinate &elem); //元素出栈,栈顶下降
void stackTraverse(bool isFromButtom); //遍历栈中所有元素
private:
Coordinate *m_pBuffer; //栈空间指针
int m_iSize; //栈容量
int m_iTop; //栈顶,栈中元素个数
};
#endif#include
#include
#include"MyStack.h"
using namespace std;
MyStack::MyStack(int size){
m_iSize=size;
m_pBuffer=new Coordinate[m_iSize];
m_iTop=0;
}
MyStack::~MyStack()
{
delete[] m_pBuffer;
m_pBuffer=NULL;
}
bool MyStack::stackEmpty()
{
if(m_iTop==0)
{
return true;
}
return false;
}
bool MyStack::stackFull()
{
if(m_iTop==m_iSize)
{
return true;
}
return false;
}
void MyStack::cleanStack()
{
m_iTop=0;
}
int MyStack::stackLenth()
{
return m_iTop;
}
bool MyStack::push(Coordinate elem)
{
if(stackFull()){ //如果不满,就入栈
return false;
}
m_pBuffer[m_iTop]=elem;
m_iTop++;
return true;
}
bool MyStack::pop(Coordinate &elem)
{
if(stackEmpty()){ //如果不为空就出栈
return false;
}
//由于栈顶指针始终指向的栈顶的上面一个元素,
//也就是说是一个空元素,所以说要先执行--
//操作,然后才能获取到栈顶元素,否则会报
//空指针异常。
m_iTop--;
elem=m_pBuffer[m_iTop];
return true;
}
void MyStack::stackTraverse(bool isFromButtom)
{
if(isFromButtom)
{
for(int i=0;i
=0;i--)
{
m_pBuffer[i].printCoordinate();
}
}
}
#ifndef COORDINATE_H
#define COORDINATE_H
class Coordinate
{
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" using namespace std; // //MyStack(int size); //分配内存,初始化栈空间,设定栈容量,栈顶 //~MyStack(); //回收栈空间内存 //bool stackEmpty(); //判定栈是否为空,为空返回true,非空返回false。 //bool stackFull(); //判断栈是否已满,已满返回true,不满返回false。 //void cleanStack(); //清空栈 //int stackLenth(); //已有元素的个数 //void push(char elem); //元素入栈,栈顶上升 //char pop(char &elem); //元素出栈,栈顶下降 //void stackTraverse(); //遍历栈中所有元素 目的:掌握栈的实现原理和运行机制#include
#include
#include"MyStack.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<<"栈为满"<
以上内容来源于慕课网。