实现顺序栈的各种基本运算的算法
实现顺序栈的各种基本运算的算法,并在此基础上设计一个主程序完成各种基本功能!
#include<iostream> using namespace std; #define MaxSize 50 typedef char ElemType; typedef struct { ElemType data[MaxSize]; int top; }SqStack; void InitStack(SqStack * &s) //建立一个空栈,即将栈顶指针指向-1即可 { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } void ClearStack(SqStack * &s) //释放栈s占用的存储空间 { free(s); } int StackLength(SqStack *s) { return (s->top +1); } int StackEmpty(SqStack *s) { return (s->top==-1); } int Push(SqStack *&s,ElemType e) { if(s->top==MaxSize-1) return 0; s->top++; s->data[s->top]=e; return 1; } int Pop(SqStack * &s,ElemType &e) { if(s->top ==-1) return 0; e=s->data[s->top]; s->top--; return 1; } int GetTop(SqStack * &s,ElemType &e) { if(s->top==-1) return 0; e=s->data[s->top]; return 1; } void DispStack (SqStack *s) //从栈顶到栈底顺序显示所有元素 { int i; for(i=s->top;i>=0;i--) { printf("%c",s->data[i]); } printf("\n"); } void main() { SqStack *s; InitStack(s); StackEmpty(s); printf("栈为%s\n",(StackEmpty(s)?"空":"非空")); Push(s,'a'); Push(s,'b'); Push(s,'c'); Push(s,'d'); Push(s,'e'); StackEmpty(s); printf("栈为%s\n",(StackEmpty(s)?"空":"非空")); DispStack(s); }