順序棧的數據結構如下:
typedef struct { ElemType data[MaxSize]; //棧數據 int top; //棧頂指針 }SqStack;
void InitStack(SqStack* &s); //初始化棧 void DestroyStack(SqStack* &s); //銷毀棧 int StackLength(SqStack* s); //求棧的長度 int StackEmpty(SqStack* s); //棧是否為空 int Push(SqStack* &s,ElemType e); //進棧 int Pop(SqStack* &s,ElemType &e); //出棧 int GetTop(SqStack* s,ElemType &e); //取棧頂元素 void DispStack(SqStack* s); //輸出棧
#include#include #include #define ElemType int #define MaxSize 1000 #define GET_ARRAY_LENGTH(array) (sizeof(array)/sizeof(array[0])) using namespace std; typedef struct { ElemType data[MaxSize]; //棧數據 int top; // }SqStack; void InitStack(SqStack* &s); //初始化棧 void DestroyStack(SqStack* &s); //銷毀棧 int StackLength(SqStack* s); //求棧的長度 int StackEmpty(SqStack* s); //棧是否為空 int Push(SqStack* &s,ElemType e); //進棧 int Pop(SqStack* &s,ElemType &e); //出棧 int GetTop(SqStack* s,ElemType &e); //取棧頂元素 void DispStack(SqStack* s); //輸出棧 void InitStack(SqStack* &s){ s=(SqStack* )malloc(sizeof(SqStack)); s->top=-1; } void DestroySqStack(SqStack* &s){ free(s); } int StackLength(SqStack* s){ return (s->top+1); } int StackEmpty(SqStack* s){ return (s->top==-1); } void DispStack(SqStack* s){ for(int i=s->top;i>-1;i--) cout< data[i]<<" "; cout< top+1==MaxSize)return -1; else{ s->data[s->top+1]=e; s->top++; return 1; } } int Pop(SqStack* &s,ElemType &e){ if(s->top==-1)return -1; else{ e=s->data[s->top]; s->top--; return 1; } } int GetTop(SqStack* s,ElemType &e){ if(s->top==-1)return -1; else { e=s->data[s->top]; return 1; } } int main(){ int i=0; ElemType e; SqStack* s=NULL; ElemType a[]={3,76,4,25,7,8,2,43,212}; InitStack(s); for(int i=0;i
代碼運行 結果如下: