ITPub博客

首页 > IT职业 > IT图书 > 具体实现代码@数据结构探险—栈篇 3-1

具体实现代码@数据结构探险—栈篇 3-1

IT图书 作者:ideasdo 时间:2021-09-09 09:05:37 0 删除 编辑

有需要的自取。。

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 /* MyStack_hpp */
file:MyStack.cpp

#include "MyStack.hpp"
#include "Coordinate.hpp"
#include 

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::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 =0;i--){
            m_pBuffer[i].printCoordinate();
        }
    }
}
file:Coordinate.hpp

#ifndef Coordinate_hpp
#define Coordinate_hpp

#include 

class Coordinate{
public:
    Coordinate(int x = 0,int y = 0);
    void printCoordinate();

private:
    int m_iX;
    int m_iY;
};

#endif /* Coordinate_hpp */
file:Coordinate.cpp

#include "Coordinate.hpp"
#include 

using namespace std;

Coordinate::Coordinate(int x,int y){
    m_iX = x;
    m_iY = y;
}

void Coordinate::printCoordinate(){
    cout 
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 stackLength() stackTraverse(true);

    pStack->clearStack();

    if(pStack->stackEmpty()){
        cout stackFull()){
        cout 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4237/viewspace-2799322/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    0
  • 访问量
    544