链表的优缺点
优点:
- 任意位置插入删除数据效率高(O(1))
- 按需申请空间
缺点:
- 不支持下标的随机访问
- CPU高速缓存命中率会更低
顺序表的优缺点
缺点:
- 插入删除数据,效率为O(N)
- 空间不够,需要扩容,扩容需要付出代价,一般会伴随空间浪费
优点:
- 下标的随机访问
- 尾插尾删效率不错
- CPU高速缓存命中率会更高
栈
- 特殊的线性表,只允许在固定的一端进行插入和删除元素的操作。进行数据插入和删除的一端叫栈顶,另一端叫栈底
- 遵循先入后出的规则
- 压栈:入数据在栈顶
- 出栈:出数据也在栈顶
实现栈的方式:
数组栈
链式栈(单链表)
综合两个的情况,用数组栈使用更为方便
定义栈的结构
typedef int STDataType;
typedef struct Stack
{
STDataType* _a;
int _top; // 栈顶
int _capacity; // 容量
}Stack;
初始化栈
这里需要注意的是,如果把top初始化为0时,那么每添加一个元素,top指针就指向元素的后一个位置,而如果把top置为-1,则top指针就会指向元素的位置;当其值设置以后,那么后面的top的使用也会不同。在本代码中,设置其值为0.
void StackInit(Stack* ps)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = 0;
ps->_top = 0;//top指针指向元素的下一个位置
}
入栈 (压栈)
void StackPush(Stack* ps, STDataType data)//???
{
assert(ps);
if (ps->_capacity == ps->_top)
{
int newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
STDataType* a = (STDataType*)realloc(ps->_a,sizeof(STDataType) * newcapacity);
//空间的类型要与数组类型一致
if (a == NULL)
{
perror("realloc fail");
return;
}
ps->_a = a;
ps->_capacity = newcapacity;
}
ps->_a[ps->_top] = data;
ps->_top++;
}
出栈
void StackPop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->_top--;
}
获取栈顶元素
因为在本次代码中设置了top值为0,所以在获取栈顶元素时,需要把top减减,top指针才会指向栈顶元素。
STDataType StackTop(Stack* ps)
{
assert(ps);
return ps->_a[ps->_top-1];//???
}
获取栈中有效元素个数
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}
检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
return ps->_top == 0;
}
销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->_a);
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}
完整代码和运行结果
#pragma once
#include<stdio.h>
#include<assert.h>
// 支持动态增长的栈
typedef int STDataType;
typedef struct Stack
{
STDataType* _a;
int _top; // 栈顶
int _capacity; // 容量
}Stack;
// 初始化栈
void StackInit(Stack* ps)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = 0;
ps->_top = 0;//top指针指向元素的下一个位置
}
// 入栈
void StackPush(Stack* ps, STDataType data)//???
{
assert(ps);
if (ps->_capacity == ps->_top)
{
int newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
STDataType* a = (STDataType*)realloc(ps->_a,sizeof(STDataType) * newcapacity);//空间的类型要与数组类型一致
if (a == NULL)
{
perror("realloc fail");
return;
}
ps->_a = a;
ps->_capacity = newcapacity;
}
ps->_a[ps->_top] = data;
ps->_top++;
}
// 出栈
void StackPop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->_top--;
}
// 获取栈顶元素
STDataType StackTop(Stack* ps)
{
assert(ps);
return ps->_a[ps->_top-1];//???
}
// 获取栈中有效元素个数
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
return ps->_top == 0;
}
// 销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->_a);
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}
int main()
{
Stack s;
StackInit(&s);
StackPush(&s, 111);
StackPush(&s, 1);
StackPush(&s, 2);
StackPush(&s, 3);
StackPush(&s, 4);
StackPush(&s, 47);
printf("%d\n", StackSize(&s));
while (!StackEmpty(&s))
{
printf("%d ", StackTop(&s));
StackPop(&s);
}
StackDestroy(&s);
return 0;
}