1.栈的概念
一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作 。进行数据插入和删除操作的一端称为栈 顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO ( Last In First Out )的原则。
2.顺序栈的实现
2.1顺序栈的头文件及数据类型定义
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
typedef int STData_t;
typedef struct Stack{
STData_t *a;
int top;
int capacity;
}ST;
2.2顺序栈的接口函数
//接口
void StackInit(ST* ps);
void StackDestory(ST* ps);
void StackPush(ST* ps,STData_t x);
void StackPop(ST* ps);
STData_t StackTop(ST* ps);
int StackSize(ST* ps);
bool StackEmpty(ST* ps);
2.3顺序栈的接口函数实现
//初始化
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0; //ps->top = -1 等于0指向栈顶下一个,-1指向栈顶
ps->capacity = 0;
}
//插入数据
void StackPush(ST* ps,STData_t x)
{
assert(ps);
if(ps->capacity == ps->top)
{
int newCapaCity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STData_t* temp = realloc(ps->a,sizeof(STData_t) * newCapaCity);
if(temp == NULL)
{
printf("realloc fail\n");
exit(-1);
}
ps->a = temp;
ps->capacity = newCapaCity;
}
ps->a[ps->top] = x;
ps->top++;
}
//对数据进行释放
void StackDestory(ST* ps)
{
assert(ps);
free(ps);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
//删除数据
void StackPop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
ps->top--;
}
//去栈顶数据
STData_t StackTop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->a[ps->top-1];
}
//计算元素个数
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
//判断是否为空
bool StackEmpty(ST* ps)
{
assert(ps);
/*if(ps->top == 0){
return true;
}
else{
return false;
}*/
return ps->top == 0;
}
2.4测试
//测试
void TestStack()
{
ST st;
StackInit(&st);
StackPush(&st,1);
StackPush(&st,2);
StackPush(&st,3);
StackPush(&st,4);
while(!StackEmpty(&st))
{
printf("%d ",StackTop(&st));
StackPop(&st);
}
StackDestory(&st);
}
int main()
{
TestStack();
return 0;
}