seqstack.h
#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 Inc(SeqStack *s);
void InitStack(SeqStack *s);
bool IsFull(SeqStack *s);
bool IsEmpty(SeqStack *s);void Push(SeqStack *s, ElemType x);
void Pop(SeqStack *s);
bool GetTop(SeqStack *s, ElemType *v);
void Show(SeqStack *s);
int Length(SeqStack *s);
void Clear(SeqStack *s);
void Destroy(SeqStack *s);#endif //__SEQSTACK_H__
seqstack.c
#include"SeqStack.h"
//创建一个空栈
void InitStack(SeqStack *s)
{
s->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
assert(s->base != NULL);
s->capacity = STACK_INIT_SIZE;
s->top = 0; //栈顶元素初始值为0,所以先用再自加1
}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;
return true;
}//判断是否栈已满
bool IsFull(SeqStack *s)
{
return s->top >= s->capacity;
}//判断栈是否空栈
bool IsEmpty(SeqStack *s)
{
return s->top == 0;
}//将元素x插入栈
void Push(SeqStack *s, ElemType x)
{
if(IsFull(s) && !Inc(s))
{
printf("栈空间已满,%d 不能入栈.\n",x);
return;
}s->base[s->top] = x;
s->top++;
}//出栈
void Pop(SeqStack *s)
{
if(IsEmpty(s))
{
printf("栈空间已空,不能出栈.\n");
return;
}s->top--;
}//获取栈顶元素
bool GetTop(SeqStack *s, ElemType *v)
{
if(IsEmpty(s))
{
printf("栈空间已空,不能取栈顶元素.\n");
return false;
}*v = s->base[s->top-1];
return true;
}//遍历栈
void Show(SeqStack *s)
{
for(int i=s->top-1; i>=0; --i)
{
printf("%d\n",s->base[i]);
}
printf("\n");
}//栈长度,即栈的元素个数
int Length(SeqStack *s)
{
return s->top;
}//清空栈,把s置为空栈
void Clear(SeqStack *s)
{
s->top = 0;
}//销毁栈,栈s不再存在
void Destroy(SeqStack *s)
{
free(s->base);
s->base = NULL;
s->capacity = s->top = 0;
}
main.c测试接口
#include"SeqStack.h"
void main()
{
SeqStack st;
InitStack(&st);ElemType v;
for(int i=1; i<=10; ++i)
{
Push(&st,i);
}
Show(&st);
Clear(&st);
Show(&st);Destroy(&st);
}