顺序栈的基本操作实现

来源:互联网 发布:php get json数据 编辑:程序博客网 时间:2024/05/23 20:25
#include<stdlib.h>#include<iostream>using namespace std;#define StackSize 100//顺序栈的初始分配空间typedef struct{char data[StackSize];//保存栈中元素int top;//栈指针}SqStack;void InitStack(SqStack *st)//*st为引用型参数{st->top=-1;}int push(SqStack *st,char x)//进栈运算{if(st->top==StackSize-1)//栈满return 0;else{st->top++;//栈不满st->data[st->top]=x;return 1;}}int pop(SqStack *st,char  *x)//出栈运算,*st,*x都为引用型参数{if(st->top=-1)//栈空return 0;else{*x=st->data[st->top];//栈不空st->top--;return 1;}}int gettop(SqStack *st,char *x)//取栈顶元素,x为引用型参数{if(st->top==-1)//栈空return 0;else{*x=st->data[st->top];return 1;}}int getall(SqStack *st,char *x){if(st->top==-1)return 0;else{while(st->top!=-1){*x=st->data[st->top];cout<<*x;st->top--;}}}int StackEmpty(SqStack *st)//判断栈是否为空{if(st->top==-1)return 1;elsereturn 0;}void main(){SqStack st;char e;InitStack(&st);cout<<"栈";if(StackEmpty(&st)==1)cout<<"空"<<endl;elsecout<<"不空"<<endl;cout<<"a 进栈"<<endl;push(&st,'a');cout<<"b 进栈"<<endl;push(&st,'b');cout<<"c 进栈"<<endl;push(&st,'c');cout<<"d 进栈"<<endl;push(&st,'d');cout<<"e 进栈"<<endl;push(&st,'e');cout<<"栈";if(StackEmpty(&st)==1)cout<<"空"<<endl;elsecout<<"不空"<<endl;gettop(&st,&e);cout<<"栈顶元素"<<endl;cout<<"出栈次序";getall(&st,&e);while(!StackEmpty(&st)){pop(&st,&e);cout<<e;}cout<<"\n";}

原创粉丝点击