實現順序棧的各種基本運算的算法,並在此基礎上設計一個主程序完成各種基本功能!
#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); }