有需要的自取。。
file:MyStack.hpp #ifndef MyStack_hpp #define MyStack_hpp #include#include "Coordinate.hpp" class MyStack{ public: MyStack(int size); ~MyStack(); bool stackFull(); bool stackEmpty(); void clearStack(); int stackLength(); bool push(Coordinate elem); bool pop(Coordinate &elem); void stackTraverse(bool isFromBottom); private: Coordinate *m_pBuffer; int m_iSize; int m_iTop; }; #endif
file:MyStack.cpp #include "MyStack.hpp" #include "Coordinate.hpp" #includeusing 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::stackFull(){ return m_iTop==m_iSize?true:false; } bool MyStack::stackEmpty(){ return m_iTop==0?true:false; } void MyStack::clearStack(){ m_iTop = 0; } int MyStack::stackLength(){ return m_iTop; } bool MyStack::push(Coordinate elem){ if(stackFull()){ return false; } else{ m_pBuffer[m_iTop] = elem; m_iTop++; return true; } } bool MyStack::pop(Coordinate &elem){ if(stackEmpty()){ return false; } else{ m_iTop--; elem = m_pBuffer[m_iTop]; return true; } } void MyStack::stackTraverse(bool isFromBottom){ if(isFromBottom){ for(int i =0;i < m_iTop;i++) { m_pBuffer[i].printCoordinate(); } } else{ for(int i = m_iTop-1;i >=0;i--){ m_pBuffer[i].printCoordinate(); } } }
file:Coordinate.hpp #ifndef Coordinate_hpp #define Coordinate_hpp #includeclass Coordinate{ public: Coordinate(int x = 0,int y = 0); void printCoordinate(); private: int m_iX; int m_iY; }; #endif
file:Coordinate.cpp #include "Coordinate.hpp" #includeusing namespace std; Coordinate::Coordinate(int x,int y){ m_iX = x; m_iY = y; } void Coordinate::printCoordinate(){ cout << "(" << m_iX << "," << m_iY << ")" << endl; }
file:demo.cpp #include#include #include "MyStack.hpp" using namespace std; int main(void){ MyStack *pStack = new MyStack(5); Coordinate coor1(1,2); Coordinate coor2(2,3); Coordinate coor3(3,4); Coordinate coor4(4,5); Coordinate coor5(5,6); pStack->push(coor1); pStack->push(coor2); pStack->push(coor3); pStack->push(coor4); pStack->push(coor5); pStack->stackTraverse(true); Coordinate elem(0,0); pStack->pop(elem); elem.printCoordinate(); cout << pStack->stackLength() << endl; pStack->stackTraverse(true); pStack->clearStack(); if(pStack->stackEmpty()){ cout << "栈为空" << endl; } if(pStack->stackFull()){ cout << "栈为满" << endl; } delete pStack; pStack = NULL; }



