实现一个简单的C++顺序栈。
#include <iostream>
#define MAXSIZE 6
using namespace std;
typedef int ElemType;
typedef struct {
ElemType *base;
ElemType *top;
} sqStack;
bool initStack(sqStack &S) {
S.base = new ElemType[MAXSIZE];
if (!S.base) {
return false;
}
S.top = S.base;
return true;
}
bool push(sqStack &S, ElemType e) {
if (S.top - S.base == MAXSIZE) {
cout << "Stack is full,Push failed!" << endl;
return false;
}
*S.top++ = e;
return true;
}
bool pop(sqStack &S, ElemType &e) {
if (S.top == S.base) {
cout << "Stack is empty, pop failed!" << endl;
return false;
}
e = *--S.top;
return true;
}
bool getTop(sqStack S, ElemType &e) {
if (S.top == S.base) {
cout << "Stack is empty, get top element failed!" << endl;
return false;
}
e = *(S.top - 1);
return true;
}
bool isEmpty(sqStack S) {
if (S.top == S.base) return true;
else return false;
}
bool isFull(sqStack S) {
if (S.top - S.base == MAXSIZE) return true;
else return false;
}
int main() {
sqStack s;
cout << "Init Stack." << endl;
initStack(s);
cout << "Push 1,2,3,4,5,6 ." << endl;
for (int i = 1; i < 7; i++) {
push(s, i);
}
cout << "Stack empty: " << isEmpty(s) << " ;Stack full: " << isFull(s) << endl;
cout << "Get top element of the Stack: ";
int top;
getTop(s, top);
cout << top << endl;
cout << "Pop all element from the Stack:";
int e;
while (!isEmpty(s)) {
pop(s, e);
cout << e << " ";
}
cout << endl;
return 0;
}
Output:
Init Stack.
Push 1,2,3,4,5,6 .
Stack empty: 0 ;Stack full: 1
Get top element of the Stack: 6
Pop all element from the Stack:6 5 4 3 2 1