C++ 顺序栈实现及测试:基本操作、进出栈、栈顶元素获取
#include
#define MaxSize 100 typedef char ElemType; typedef struct { ElemType data[MaxSize]; int top; }SqStack;
void InitStack(SqStack &st) { st.top = -1; }
void DestroyStack(SqStack &st) { st.top = -1; }
int Push(SqStack &st, ElemType x) { if(st.top == MaxSize - 1) return 0; st.data[++st.top] = x; return 1; }
int Pop(SqStack &st, ElemType &x) { if(st.top == -1) return 0; x = st.data[st.top--]; return 1; }
int GetTop(SqStack st, ElemType &x) { if(st.top == -1) return 0; x = st.data[st.top]; return 1; }
int StackEmpty(SqStack st) { if(st.top == -1) return 1; else return 0; }
int main() { SqStack st; InitStack(st); ElemType x;
cout << '请输入进栈元素(以空格分隔):';
while(cin >> x)
{
if(!Push(st, x))
{
cout << '栈已满!' << endl;
break;
}
}
cout << '栈是否为空:';
if(StackEmpty(st))
cout << 'Yes' << endl;
else
cout << 'No' << endl;
cout << '栈顶元素:';
if(GetTop(st, x))
cout << x << endl;
else
cout << '栈为空!' << endl;
cout << '出栈次序:';
while(Pop(st, x))
cout << x << ' ';
cout << endl;
DestroyStack(st);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pl04 著作权归作者所有。请勿转载和采集!