顺序栈的实现:
- 栈底指针始终指向栈底的位置,栈为空时栈顶指针等于栈底指针。
- 栈为满时,栈顶指针-栈底指针=栈容量。
- 栈非空时,栈顶指针永远指向栈顶元素的上一个位置。
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct {
int *base; // 栈底指针
int *top; // 栈顶指针
int stacksize; // 栈可用最大容量
}SqStack;
// 初始化
bool initStack(SqStack &S) {
S.base = new int[MAXSIZE]; // 为顺序栈分配一个最大容量为MAXSIZE的数组空间
if (!S.base) {
return false;
}
S.top = S.base; // 栈空
S.stacksize = MAXSIZE;
return true;
}
// 销毁
bool destroyStack(SqStack &S) {
if (S.base) {
delete S.base;
}
S.base = S.top = NULL;
S.stacksize = 0;
return true;
}
// 判断栈是否为空
bool isEmpty(SqStack S) {
if (S.base == S.top) {
return true;
} else {
return false;
}
}
// 判断栈是否满
bool isFull(SqStack S) {
if (S.top - S.base == S.stacksize) {
return true;
} else {
return false;
}
}
// 入栈
bool push(SqStack &S, int e) {
if (isFull(S)) { // 栈满
return false;
}
*S.top++ = e; // 压入栈,栈顶指针加1
return true;
}
// 出栈
bool pop(SqStack &S, int &e) {
if (isEmpty(S)) {
return false;
}
e = *--S.top; // 出栈,栈顶指针减1
return true;
}
// 取栈顶元素
int getTop(SqStack S) {
if (S.top != S.base) {
return *(S.top - 1);
}
return -1;
}
int main() {
SqStack S;
initStack(S);
if (isEmpty(S)) {
cout << "栈为空" << endl;
}
for (int i = 1; i <= 10; ++i) {
push(S, i);
cout << "栈顶元素:" << getTop(S) << endl;
}
for (int i = 1; i <= 10; ++i) {
int e;
pop(S, e);
cout << "出栈元素:" << e << endl;
}
return 0;
}