c++实现基本栈造作

c++实现基本栈操作:后进先出

头文件:(注意是ifndef)

#ifndef MYSTACK_H
#define MYSTACK_H

class MyStack{
public:
    MyStack(int size);  //分配内存初始化栈空间,设定栈容量,栈顶
    ~MyStack();        //回收空间
    bool stackFull();   //判定栈满
    bool stackEmpty();  //判定栈空
    void clear();       //清空栈
    int stackLength();      //栈中元素个数
    void push(char elem);   //元素入栈,栈顶上升
    char pop(); //元素出栈,栈顶下降
    void stackTraverse(bool isFromBottom);  //遍历栈
private:
    char *m_pBuffer;    //栈空间指针
    int m_size;         //栈大小
    int m_top;          //栈顶
};
#endif

关键代码及实现:

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

MyStack::MyStack(int size){
    m_size=size;
    m_pBuffer=new char[m_size];
    m_top=0;
}
MyStack::~MyStack(){
    delete []m_pBuffer;
}
int MyStack::stackLength(){
    return m_size;
}
bool MyStack::stackEmpty(){
    if (0==m_top)
    {
        return true;
    }
    return false;
}
bool MyStack::stackFull(){
    if (m_top==m_size)
    {
        return true;
    }
    return false;
}
void MyStack::clear(){
    m_top=0;
}
void MyStack::push(char elem){
    if (stackFull())
    {
    }
    m_pBuffer[m_top]=elem;
    m_top++;
}
char MyStack::pop(){
    if (stackEmpty())
    {
        throw 1;
    }
    m_top--;
    return m_pBuffer[m_top];
}
void MyStack::stackTraverse(bool isFromBottom){
    if (isFromBottom)
    {
        for (int i=0;i<m_top;i++)
        {
            cout<<m_pBuffer[i]<<" ";
        }
    }else
    for(int i=m_top-1;i>=0;i--){
        cout<<m_pBuffer[i]<<" ";
    }
}
int main(){
    MyStack *p=new MyStack(5);
    p->push('i');
    p->push('k');
    p->push('o');
    p->push('b');
    p->push('e');
    p->stackTraverse(true);
    cout<<endl;
    p->stackTraverse(false);
    cout<<endl;
    if (p->stackEmpty())
    {
        cout<<"栈为空"<<endl;
    }
    if (p->stackFull())
    {
        cout<<"栈为满"<<endl;
    }
    cout<<"出栈元素:"<<p->pop()<<endl;
    cout<<"出栈元素:"<<p->pop()<<endl;
    p->stackTraverse(true);
    return 0;
}

实现结果:
c++实现栈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值