栈:操作受限的线性表,后进先出
栈的内部存储既可以用顺序表,也可以用链表,分别称作顺序栈和链栈。
先来实现一个简单的顺序栈
C++
class MyStack {
char *buffer;
int size;
int top;
public:
MyStack(int size);
~MyStack();
bool stackEmpty();
bool stackFull();
void clearStack();
int stackLength();
void push(char elem);
void pop(char &elem);
void stackTraverse();
};
MyStack::MyStack(int size){
buffer = new char[size];
this->size = size;
top = 0;
}
MyStack::~MyStack(){
delete [] buffer;
}
bool MyStack::stackEmpty(){
return top == 0;
}
bool MyStack::stackFull(){
return top == size;
}
void MyStack::clearStack(){
top = 0;
}
int MyStack::stackLength(){
return top;
}
void MyStack::push(char elem){
buffer[top++] = elem;
}
void MyStack::pop(char &elem){
elem = buffer[--top];
}
void MyStack::stackTraverse(){
for (int i=0; i<top; i++) {
std::cout<<buffer[i]<<std::endl;
}
}
网友评论