/***************************/
/***************************/
/***************************/
#include <stdio.h>
#include <stdlib.h>
#define Error(Str) FatalError(Str)
#define FatalError(Str) fprintf(stderr,"%s\n",Str),exit(1)
#define EmptyPos (-1)
#define MiStackSize (5)
#define StackIncrement (2)
typedef int ElemType;
//#ifndef _Stack_h
//#define _Stack_h
typedef struct{
ElemType Capacity;
ElemType Top;
ElemType *Array;
}SqStack;
/**
* 1.Top=-1,如果是空栈
* 2. 元素x入栈,(1)top+1(2)stack[s.top]=x,是入栈的数
* 3. 元素x出栈(1)stack[s.top]=x;(2)top-1;
*/
int IsEmpty(SqStack s);
int IsFull(SqStack s);
SqStack* CreatStack(int Init_MaxElements );
void DisposeStack(SqStack* s);
void Push(ElemType x,SqStack* s);
ElemType Top(SqStack s);
void Pop(SqStack s);
ElemType TopAndPop(SqStack S);
//#endif
/***********************************/
int IsEmpty(SqStack s){
return s.Top==EmptyPos; // top是否是-1
}
int IsFull(SqStack s){
return s.Top==s.Capacity-1;
}
void MakeEmpty(SqStack *s){
s->Top=EmptyPos;
}
SqStack* CreatStack(int Init_MaxElements ){
SqStack *s;
if(Init_MaxElements < MiStackSize){
Error("stack size is too small!");
}
if(!(s->Array=(ElemType *)malloc(Init_MaxElements*sizeof(ElemType))))
FatalError("out of space");
s->Capacity=Init_MaxElements;
MakeEmpty(s);
}
void void DisposeStack(SqStack* s){
if(s!=NULL){
free(s->Array);
free(s);
}
}
void Push(ElemType x,SqStack* s){
if(IsFull(*s)){
s->Array=(ElemType *)realloc(s->Array,(s->Capacity+StackIncrement)*sizeof(ElemType));
}
if(!s->Array)
Error("Full stack");
else
s->Array[++s->Top] = x;
}
void Pop(SqStack* s){
if(IsEmpty(s))
Error("Empty stack");
else
s->Top--;
}
ElemType TopAndPop(SqStack* s){
if(!IsEmpty(s))
return s->Array[s->Top--];
Error("Empty stack");
return 0;
}
复习(数据结构):栈:c语言:动态数组
最新推荐文章于 2024-01-15 11:44:00 发布