栈的顺序存储结构
#define ElemType int #define Stack_Init_Szie 10 #define OK 1; #define ERROR 0; typedef struct Node{ ElemType* base; ElemType* top; int stackSize;//栈的实际大小 }SqStack; int Init(SqStack &sq){ sq.base=(ElemType *)malloc(Stack_Init_Szie*sizeof(ElemType)); if(!sq.base){ return ERROR; } sq.top=sq.base; sq.stackSize=Stack_Init_Szie; return OK; } ElemType GetTop(SqStack sq){ if(sq.top!=sq.base){ return *(--sq.top); } return ERROR; } //进栈 int Push(SqStack &sq,ElemType value){ if(sq.top-sq.base==sq.stackSize){ return ERROR; } *sq.top++ = value; return OK; } //出栈 int Pop(SqStack &sq,ElemType &value){ if(sq.base==sq.top){ printf("This Stack is empty!!\n"); return ERROR; } value=*(--sq.top); return OK; } int GetStackLength(SqStack sq){ return sq.top-sq.base; }
栈的链式存储结构
#include <stdio.h> #include <stdlib.h> #define ElemType int #define OK 1 #define ERROR 0 #define Status int typedef struct Node{ ElemType data; struct Node *next; }StackLink; void Init(StackLink *&s){ s=(StackLink*)malloc(sizeof(StackLink)); s->next=NULL; } Status Push(StackLink *&s,ElemType value){ StackLink *p; p=(StackLink *)malloc(sizeof(StackLink)); p->data=value; p->next=s->next; s->next=p; return OK; } Status Pop(StackLink *&s,ElemType &value){ StackLink *p=s->next; if(!s->next) return ERROR;//栈空 value=p->data; s->next=p->next; free(p); return OK; } void Print(StackLink *s){ StackLink *pre=s->next; while(pre!=NULL){ printf("%d\n",pre->data); pre=pre->next; } }