简单栈的实现
</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;
}