头文件
#ifndef __SEQSTACK_H__
#define __SEQSTACK_H__
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#define ElemType int
#define STACK_INIT_SIZE 8
#define STACK_INC_SIZE 3
typedef struct SeqStack
{
ElemType *base;
int capacity;
int top;
}SeqStack;
bool IsFull(SeqStack *s);
bool IsEmpty(SeqStack *s);
bool Inc(SeqStack *s);
void IniStack(SeqStack *s);
void Push(SeqStack *s,ElemType x);
void Show(SeqStack *s);
void Pop(SeqStack *s);
bool GetTop(SeqStack *s,ElemType *v);
int Length(SeqStack *s);
void Clear(SeqStack *s);
void Destroy(SeqStack *s);
#endif
Main
#include "SeqStack.h"
void main(){
SeqStack st;
ElemType v;
IniStack(&st);
for (int i=1;i<=10;++i){
Push(&st,i);
}
Show(&st);
GetTop(&st,&v);
printf("%d出栈\n",v);
Pop(&st);
Show(&st);
}
实现代码
#include "SeqStack.h"
void IniStack(SeqStack *s){
s->base=(ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
assert(s->base!=NULL);
s->capacity=STACK_INIT_SIZE;
s->top=0;
}
bool Inc(SeqStack *s){
ElemType *newbase =(ElemType *)realloc(s->base,sizeof(ElemType)*(s->capacity+STACK_INC_SIZE));
if(newbase==NULL){
printf("内存不足无法申请空间\n");
return false;
}
s->base=newbase;
s->capacity+=STACK_INC_SIZE;
}
bool IsFull(SeqStack *s){
return s->top>=s->capacity;
}
bool IsEmpty(SeqStack *s){
return s->top==0;
}
void Push(SeqStack *s,ElemType x){
if(IsFull(s)&& !Inc(s)){
printf("栈空间已满%d,不能入栈.\n",x);
return;
}
s->base[s->top++]=x;
}
void Show(SeqStack *s){
for (int i = s->top-1; i >=0; --i)
{
printf("%4d",s->base[i]);
}
printf("\n");
}
void Pop(SeqStack *s){
if (IsEmpty(s))
{
printf("栈空间已空,不能出栈\n");
}
s->top--;
}
bool GetTop(SeqStack *s,ElemType *v){
if(IsEmpty(s)){
printf("栈空间已空,不能取栈顶元素.\n");
return false;
}
*v=s->base[s->top-1];
return true;
}
int Length(SeqStack *s){
return s->top;
}
void Clear(SeqStack *s){
s->top=0;
}
void Destroy(SeqStack *s){
free(s->base);
s->base=NULL;
s->capacity=s->top=0;
}