简单静态栈实现

简单栈的实现


</pre><pre>

//Stack.cpp

enum Error_code {SUCCESS, UNDERFLOW, OVERFLOW};

typedef int Stack_entry;

const int maxstack = 5; //使用小容量方便测试

class Stack {
public:
    Stack();
    bool empty() const;  //状态不可改
    Error_code pop();  //为什么弹出的状态没有const???
    Error_code top(Stack_entry& item) const; //就是说这个top不能调用pop(),只能调用const函数,例如empty()
    Error_code push(const Stack_entry &item);
private:
    int count;
    Stack_entry entry[maxstack];
};

Stack::Stack() {
    count = 0;
}

bool Stack::empty() const {
    if (count == 0) {
        return true;
    } else {
        return false;
    }
}

Error_code Stack::pop() {
    if (count == 0) {
        return UNDERFLOW;
    } else {
        --count;
        return SUCCESS;
    }
}

Error_code Stack::push(const Stack_entry& item) {
    if (count >= maxstack) {
        return OVERFLOW;
    } else {
        entry[count] = item;
        ++count;

        return SUCCESS;
    }
}

Error_code Stack::top(Stack_entry &item) const {
    if (count == 0) {
        return UNDERFLOW;
    } else {
        item = entry[count-1]; //top()只返回当前顶端的值,count的值应该不变
        return SUCCESS;
    }
}


//main.cpp
#include <iostream>
#include "Stack.h"

using namespace std;

int main() {
    Stack myStack;

    int temp;

    myStack.push(1);
    myStack.push(3);
    myStack.push(4);
    myStack.push(8);
    myStack.push(2);  //2,8,4,3,1
    myStack.push(0);  //2,8,4,3,1

    myStack.top(temp);
    cout << temp << endl;

    myStack.pop();  //8,4,3,1

    myStack.top(temp);
    cout << temp << endl;

    myStack.push(9);  //9,8,4,3,1

    myStack.top(temp);
    cout << temp << endl;

    myStack.pop();  //8,4,3,1

    myStack.top(temp);
    cout << temp << endl;

    myStack.pop();  //4,3,1
    myStack.pop();  //3,1
    myStack.pop();  //1
    myStack.pop();  //(empty)
    myStack.pop();  //(empty)

    myStack.top(temp);  //输出为8,说明了其实top()函数最好还是要有Error_code的判断
    cout << temp << endl;

    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值