代码:
1. 注意:
- 这里分为两个版本了,分别为把
栈顶指针
初始化为-1
和 1
的情况,大家需要认真去阅读,以免发生错误。
2. 代码实体:
#include <iostream>
#include <stdio.h>
#define MaxSize 10
using namespace std;
typedef int ElemType;
typedef struct SqStack{
int top;
ElemType data[MaxSize];
}SqStack;
void InitStack(SqStack &S){
S.top = -1;
}
void InitStack1(SqStack &S){
S.top = 0;
}
bool StackEmpty(SqStack S){
if (S.top == -1) return true;
else return false;
}
bool StackEmpty1(SqStack S){
if (S.top == 0) return true;
else return false;
}
bool Push(SqStack &S, ElemType x){
if (S.top == MaxSize - 1)
return false;
S.data[++S.top] = x;
return true;
}
bool Push1(SqStack &S, ElemType x){
if (S.top == MaxSize)
return false;
S.data[S.top++] = x;
return true;
}
bool Pop(SqStack &S, ElemType &x){
if (S.top == -1) return false;
x = S.data[S.top--];
return true;
}
bool Pop1(SqStack &S, ElemType &x){
if (S.top == 0) return false;
x = S.data[--S.top];
return true;
}
bool GetTop(SqStack S, ElemType &x){
if(S.top == -1) return false;
x = S.data[S.top];
return true;
}
bool GetTop1(SqStack S, ElemType &x){
if(S.top == 0) return false;
x = S.data[S.top];
return true;
}
int main(int argc, const char * argv[]) {
SqStack S;
InitStack(S);
cout << StackEmpty(S) << endl;
cout << "---------------------------------" << endl;
Push(S, 1);
Push(S, 2);
Push(S, 3);
cout << StackEmpty(S) << endl;
cout << "---------------------------------" << endl;
ElemType x;
for (int i = 0; i <= S.top; i ++) {
cout << S.data[i] << endl;
}
cout << StackEmpty(S) << endl;
cout << "---------------------------------" << endl;
return 0;
}