栈,一种特殊的线性表,只允许在固定的 一端进行插入和删除操作,栈中的数据遵循后进先出原则。可以用数组和链表来表示栈。
(1)如果使用链式栈,如果用尾作栈顶,尾插尾删,要设计成双向链表,否则删除数据效率低。如果用头作栈顶,头插头删,可以设计成单链表。
(2)综合这两种,如果非要选一种,数组栈稍微好一点。
1,定义栈
typedef struct Stack {
STDatatype* a; //使用动态的数组
int top; //栈顶元素下一个元素的下标
int capacity;//栈的容量
}ST;
2,栈的基本操作
void StackInit(ST* ps);//初始化
void StackDestroy(ST* ps);//销毁栈
void StackPush(ST* ps, STDatatype x);//入栈
void StackPop(ST* ps);//出栈
bool StackEmpty(ST* ps);//判断栈是否为空
int StackSize(ST* ps);//栈中元素的个数
STDatatype StackTop(ST* ps);//栈顶元素
实现
#pragma once
#include"stack.h"
void StackInit(ST* ps)
{
assert(ps);//指向结构体的指针不能为空
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackDestroy(ST* ps)
{
assert(ps);
if(ps->a)
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackPush(ST* ps, STDatatype x)
{
assert(ps);
if (ps->top == ps->capacity)//如果栈已满,则需要扩容,一般扩容为原来的1.5或2倍;
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//刚开始没有容量时,就随便定一个容量,有容量就扩容为原来的2倍;
STDatatype *temp = realloc(ps->a, sizeof(STDatatype)*newcapacity);//刚开始栈为空时,使用realloc与使用malloc一样;
if (temp == NULL)
{
printf("realloc fail\n");
exit(-1);
}
ps->a = temp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));//栈不为空继续
ps->top--;
}
bool StackEmpty(ST* ps)
{
assert(ps);
if (ps->top == 0)
return true;
else
return false;
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
STDatatype StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}