数据结构--栈--c++实现

stack.h

#ifndef mystack_h
#define mystack_h

class myStack
{
public:
    myStack(int size);
    virtual ~myStack();
    bool stackEmpty();
    bool stackFull();
    void clearStack();
    int stackLength();
    bool push(char elem);
    bool pop(char &elem);
    void stackTraverse(bool rev);
private:
    char *_ptr;
    int _size;
    int _top;
};

stack.cpp

#include <iostream>
#include "mystack.h"
using namespace std;

myStack::myStack(int size)
{
    _size = size;
    _ptr = new char[size];
    _top = 0;
}

myStack::~myStack()
{
    delete _ptr;
    _ptr = nullptr;
}

bool myStack::stackEmpty(){
    if (_top == 0)
    {
        return true;
    }else
    {
        return false;
    }
}

bool myStack::stackFull(){
    if (_top == _size)
    {
        return true;
    }else
    {
        return false;
    }
}

void myStack::clearStack(){
    _top = 0;
}

int myStack::stackLength(){
    return _top;
}

bool myStack::push(char elem){
    if (stackFull())
    {
        return false;
    } 
    else
    {
        _ptr[_top] = elem;
        _top++;
        return true;
    }
}

bool myStack::pop(char &elem){
    if (stackEmpty())
    {
        return false;
    } 
    else
    {
        _top--;
        elem = _ptr[_top];
        return true;
    }
}

void myStack::stackTraverse(bool rev){
    if (rev)
    {
        for (int i = 0;i<_top;i++)
    {
        cout<<endl<<_ptr[i]<<endl;
    }
    } 
    else
    {
        for (int i = _top-1;i>=0;i--)
    {
        cout<<endl<<_ptr[i]<<endl;
    }
    }
}

demo.cpp

#include <iostream>
#include "mystack.h"
using namespace std;

int main(){
    myStack *p = new myStack(7);
    if (p->stackEmpty())
    {
        cout<<"zhankong"<<endl;
    }else{cout<<"zhanbukong"<<endl;}
    p->push('i');
    p->push('l');
    p->push('o');
    p->push('v');
    p->push('e');
    p->push('u');
    p->push('!');
    cout<<p->stackLength()<<endl;
    p->stackFull();
    char a;p->pop(a);cout<<a<<endl;
    if (p->stackFull())
    {
        cout<<"zhanman"<<endl;
    }else{cout<<"zhanbuman"<<endl;}
    p->stackTraverse(1);p->stackTraverse(0);
    p->clearStack();
    if (p->stackEmpty())
    {
        cout<<"zhankong"<<endl;
    }else{cout<<"zhanbukong"<<endl;}
    cout<<p->stackLength()<<endl;

    delete p;
    p = nullptr;

    system("pause");
    return 0;
}
全部评论

相关推荐

10-06 12:46
门头沟学院 Java
跨考小白:定时任务启动
点赞 评论 收藏
分享
小红书 后端开发 总包n+8w+期权
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务