2.2.2 堆栈的顺序结构存储实现
堆栈的顺序存储结构通常由一个一位数组和一个记录栈顶位置的变量组成。
代码实现
包括了建立空堆栈、入栈、出栈、判断栈空栈满等函数的实现。
#include "stdio.h"
#include "stdlib.h"
#define ERROR -2
typedef int Position;
struct SNode{
int *Data;
Position top;
int MaxSize;
};
typedef struct SNode *Stack;
Stack CreatStack(int MaxSize){
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Data=(int *)malloc(MaxSize*sizeof(int));
S->top=-1;
S->MaxSize=MaxSize;
return S;
}
bool IsEmpty(Stack PtrS){
return (PtrS->top==-1);
}
bool IsFull(Stack PtrS){
return (PtrS->top==PtrS->MaxSize-1);
}
bool Push(Stack PtrS,int X){
if(IsFull(PtrS)){
printf("堆栈满!\n");
return false;
}else{
PtrS->Data[++(PtrS->top)]=X;
return true;
}
}
int Pop(Stack PtrS){
if(IsEmpty(PtrS)){
printf("堆栈空!\n");
return ERROR;//ERROR是元素类型的特殊值,标志错误
}else{
return PtrS->Data[(PtrS->top)--];
}
}
int main(){
Stack S= CreatStack(10);
printf("%d\n",Pop(S));
Push(S,1);
Push(S,2);
Push(S,3);
printf("%d\n",Pop(S));
printf("%d\n",Pop(S));
printf("%d\n",Pop(S));
return 0;
}