#include<iostream> #define N 5 using namespace std; typedef struct SqStack{ int * data; //数据指针 int size; //当前栈存放元素个数 int top; //栈定指针 }Stack; void Meanu(); //界面菜单 void RunSystem(Stack &s); void InitStack(Stack &s); //初始化栈 void DestoryStack(Stack &s); //销毁栈 bool Push(Stack &s,int e); //进栈 bool Pop(Stack &s,int &e); //出栈 void PrintStack(Stack s); //打印栈中的所有元素 bool GetTopElem(Stack s); //读取栈顶元素 int main(){ Stack s; InitStack(s); RunSystem(s); DestoryStack(s); return 0; } void Meanu(){ cout << "***********************************" << endl; cout << "**********1.入栈*******************" << endl; cout << "**********2.出栈*******************" << endl; cout << "**********3.获取栈顶元素***********" << endl; cout << "**********4.打印栈中所有元素*******" << endl; cout << "**********0.退出程序***************" << endl; cout << "*******请输入相应的功能序号********" << endl; cout << "***********************************" << endl; } void RunSystem(Stack &s){ int key; //用户输入 int e; while(true){ Meanu(); //菜单页面 cin >> key; switch(key){ case 0: goto ESCAPSE; //利用goto跳出while循环 case 1: cout << "请输入要入栈的值: "; cin >> e; Push(s,e); cout << endl; break; case 2: Pop(s,e); cout << endl; break; case 3: GetTopElem(s); cout << endl; break; case 4: PrintStack(s); cout << endl; break; default: cout << "您的输入有误,请重新输入!" <<endl; } } ESCAPSE:; } void InitStack(Stack &s){ s.data = new int[N]; //在堆中开辟空间 s.top = -1; //初始化栈的顶部指针 s.size = 0; //初始化栈中元素个数 cout << "栈初始化成功" << endl; } void DestoryStack(Stack &s){ delete s.data; cout << "栈销毁成功" << endl; } bool Push(Stack &s,int e){ //判断栈是否已满,如果栈满则不可入栈 if(s.top == N-1 || s.size == N){ cout << "当前栈已满,不可入栈" << endl; return false; } s.top++; s.size++; s.data[s.top] = e; cout << "进栈成功" << endl; return true; } bool Pop(Stack &s,int &e){ if(s.top == -1 || s.size == 0){ cout << "当前栈为空,无元素可出栈" << endl; return false; } e = s.data[s.top]; s.top--; s.size--; cout << "出栈成功" << endl; cout << "当前出栈的元素值为:" << e << endl; return true; } void PrintStack(Stack s){ if(s.top == -1 || s.size == 0){ //判断当前栈是否为空 cout << "当前栈为空" << endl; cout << "-----------------------------------" << endl; cout << "|" << endl; cout << "-----------------------------------" << endl; }else{ cout << "-----------------------------------" << endl; for(int i=0;i<=s.top;i++){ cout << "| " << s.data[i] << " "; } cout << endl; cout << "-----------------------------------" << endl; } } bool GetTopElem(Stack s){ if(s.top == -1 || s.size == 0){ //判断当前栈是否为空 cout << "当前栈为空,没有任何元素" << endl; return false; } cout << "栈顶元素值为:" << s.data[s.top] << endl; return true; }