要模拟栈,我们首先要清楚栈(Stack)的特性:先进后出,后进先出
接着要清楚栈的结构,我们可以以下面方式表示:
struct MyStack{
int capacity,top;
int *A;
};
再是模拟栈内元素的进出:
元素的进首先要判断栈是否满(FULL)了:
inline bool isFull(MyStack *stk){
return stk->top >= stk->capacity-1;
}
进(push):
int push(MyStack *stk, int item){
//检查栈是否满
if(isFull(stk)){
cout<<"Stack is full, push error!\n";
return -1;
}
stk->top++;
stk->A[stk->top]=item;
return 0;
}
元素的出首先要判断栈是否空(empty)了:
inline bool isEmpty(MyStack *stk){
return !stk->top;
}
出(pop):
int pop(MyStack *stk){