赞
踩
代码如下:
#include <iostream> using namespace std; typedef struct sqstack //顺序栈定义 { int data[10]; int top; }Sqstack; void initstack(struct sqstack &Sqstack) //初始化栈 { Sqstack.top=-1; } int isempty(struct sqstack &Sqstack) //判断栈是否空 { if(Sqstack.top==-1) { cout<<" 顺序栈为空 "<<endl; return 1; } else { cout<<" 顺序栈不为空 "<<endl; } return 0; } int push(struct sqstack &Sqstack,int x) //插入元素x作为新的栈顶元素 { if(Sqstack.top==9) { cout<<" 错误 "<<endl; return 0; } Sqstack.top=Sqstack.top+1; Sqstack.data[Sqstack.top]=x; return 1; } int gettop(struct sqstack Sqstack,int &e)//得到栈顶元素的值 { if(Sqstack.top==-1) { cout<<" NULL(空表) "<<endl; return 0; } e=Sqstack.data[Sqstack.top]; return 1; } int pop(struct sqstack &Sqstack,int &x)//删除栈顶元素并用x返回它 { if(Sqstack.top==-1) { return 0; } x=Sqstack.data[Sqstack.top]; Sqstack.top=Sqstack.top-1; return 1; } int main() { #define maxsize 10;//不清楚为什么这句无效 struct sqstack Sqstack; cout<<" 初始化顺序栈 "<<endl; initstack(Sqstack); isempty(Sqstack); int x; cout<<" 请输入插入的元素:"; cin>>x; push(Sqstack,x); isempty(Sqstack); int e; cout<<" 栈顶元素为: "; gettop(Sqstack,e); cout<<e<<endl; cout<<" 删除并得到栈顶元素x: "; pop(Sqstack,x); cout<< x; isempty(Sqstack); return 0; }
运行结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。