一、栈
1.1栈的概念及结构
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作,进行数据插入和删除操作的一端称为栈顶,另一端称为栈底,栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则
1.2栈的实现
栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些,因为数组在尾上插入数据的代价比较小
顺序栈基本操作
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct stack
{
STDataType* a;
int top;
int capacity;
}stack;
1)顺序栈初始化
void StackInit(stack* ps)//初始化
{
assert(ps != NULL);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
2)顺序栈销毁
void StackDestroy(stack* ps)//销毁
{
assert(ps != NULL);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity=0;
}
3)顺序栈入栈
void StackPush(stack* ps, STDataType x)//入栈
{
assert(ps != NULL);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType)*newcapacity);
if (tmp == NULL)
{
exit(1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
4)顺序栈判空
bool StackEmpty(stack* ps)//判断栈是否为空
{
assert(ps != NULL);
return ps->top==0;
}
5)顺序栈出栈
void StackPop(stack* ps)//出栈
{
assert(ps != NULL);
assert(!StackEmpty(ps));
ps->top--;
}
6)取栈顶元素
STDataType Stacktop(stack* ps)//取栈顶元素
{
assert(ps != NULL);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}
7)元素个数
int StackSize(stack* ps)//元素个数
{
assert(ps != NULL);
return ps->top;
}