栈:动态集合。后进先出。三种操作的执行时间都为O(1)。
伪代码如下:但是我们需要考虑对上溢下溢的检查。
#include <iostream>
using namespace std;
//定义栈
const int n = 100;
struct stack {
int top;
int array[n];
};
typedef struct stack* Stack;
//初始化栈
void init(Stack s) {
s->top = 0;
}
//判断栈是否为空
bool empty(Stack s) {
if (s->top == 0) {
return true;
}
return false;
}
//push
void push(Stack s, int x) {
if (s->top == n) {
cerr << "栈满,继续push会上溢" << endl;
return;
}
s->top = s->top + 1;
s->array[s->top] = x;
}
//pop
int pop(Stack s) {
if (empty(s)) {
cerr << "栈空,继续pop会下溢" << endl;
return 0;
}
s->top = s->top - 1;
return s->array[s->top + 1];
}
int main() {
int x = 77;
Stack S;
S= (struct stack*)malloc(sizeof(struct stack));
init(S);
push(S, x);
pop(S);
pop(S);
push(S, x);
push(S, x);
pop(S);
pop(S);
cout<<empty(S)<<endl;
system("pause");
return 0;
}