ITPub博客

首页 > IT职业 > IT职场 > 具体实现代码@数据结构探险—栈篇 2-4

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

IT职场 作者:keehoo 时间:2021-09-09 09:05:37 0 删除 编辑

具体实现代码@数据结构探险—栈篇 2-4
有需要的自取。


file:MyStack.hpp

#ifndef MyStack_hpp
#define MyStack_hpp

#include 

class MyStack{
public:
    MyStack(int size);
    ~MyStack();
    bool stackFull();
    bool stackEmpty();
    void clearStack();
    int stackLength();
    bool push(char elem);
    bool pop(char &elem);
    void stackTraverse(bool isFromBottom);
private:
    char *m_pBuffer;
    int m_iSize;
    int m_iTop;

};

#endif /* MyStack_hpp */

file:MyStack.cpp

#include "MyStack.hpp"
#include 

using namespace std;

MyStack::MyStack(int size){
    m_iSize = size;
    m_pBuffer = new char[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(char elem){
    if(stackFull()){
        return false;
    }
    else{
        m_pBuffer[m_iTop] = elem;
        m_iTop++;
        return true;
    }
}

bool MyStack::pop(char &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--){
            cout 

file demo.cpp

#include 
#include 
#include "MyStack.hpp"

using namespace std;

int main(void){
    MyStack *pStack = new MyStack(5);

    pStack->push('a');
    pStack->push('e');
    pStack->push('i');
    pStack->push('o');
    pStack->push('u');

    pStack->stackTraverse(true);

    char elem = 0;
    pStack->pop(elem);
    cout stackLength() stackTraverse(true);

    pStack->clearStack();

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

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

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

注册时间:2019-08-12

  • 博文量
    0
  • 访问量
    632