#include <stdio.h>#include <malloc.h>#define MaxSize 100//順序棧的存儲結構typedef char ElemType;typedef struct{ ElemType data[MaxSize]; int top; //棧頂指針} SqStack;//初始化棧void InitStack(SqStack *&s){ s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1;//棧頂指針置為-1}//銷毀棧void DestroyStack(SqStack *&s){ free(s);}//判斷棧是夠為空int StackEmpty(SqStack *s){ return (s->top==-1);}//進棧bool Push(SqStack *&s,ElemType e){ if(s->top==MaxSize-1)//判斷棧是否棧滿防止溢出 return false; s->top++;//棧頂指針增加一 s->data[s->top]=e; return true;}//出棧bool Pop(SqStack *&s,ElemType &e){ if(s->top==-1)//棧為空的情況,即棧下溢出 return false; e=s->data[s->top]; s->top--; return true;}//取棧頂元素bool GetTop(SqStack *s,ElemType &e){ if(s->top==-1)//棧為空的情況,即棧下溢出 return false; e=s->data[s->top]; return true;}int main(){ ElemType e; SqStack *s; PRintf("棧s的基本運算如下:/n"); printf(" (1)初始化棧s/n"); InitStack(s); printf(" (2)棧為%s/n",(StackEmpty(s)?"空":"非空")); printf(" (3)依次進棧元素a,b,c,d,e/n"); Push(s,'a'); Push(s,'b'); Push(s,'c'); Push(s,'d'); Push(s,'e'); printf(" (4)棧為%s/n",(StackEmpty(s)?"空":"非空")); printf(" (5)出棧序列:"); while (!StackEmpty(s)) { Pop(s,e); printf("%c ",e); } printf("/n"); printf(" (6)棧為%s/n",(StackEmpty(s)?"空":"非空")); printf(" (7)釋放棧/n"); DestroyStack(s); return 0;}運行結果:
新聞熱點
疑難解答