数据结构——栈

简介: 数据结构——栈

什么是栈

栈是一种特殊的线性结构,对数据增加及其删除只能在一端进行操作。

进行数据删除及增加的一端为栈顶,另一端为栈底。

增加数据为压栈。删除数据为出栈。

创建类型

typedef int StackTypeDate;
typedef struct stack
{
  StackTypeDate* arr;
  int top;
  int capacity;
}Stack;

初始栈

void InitStack(Stack* ps)
{
  assert(ps);
  ps->arr = NULL;
  ps->top = ps->capacity = 0;
}

压栈

压栈的时候要察看栈是不是满了,以及它为空的情况。

void StackPush(Stack* ps, StackTypeDate x)
{
  assert(ps);

  if (ps->capacity == ps->top)
  {
    int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
    ps->arr = (StackTypeDate*)realloc(ps->arr,sizeof(StackTypeDate) * newcapacity);
    ps->capacity = newcapacity;
  }

  ps->arr[ps->top] = x;
  ps->top++;
}

出栈

void StackPop(Stack* ps)
{
  assert(ps);
  assert(!StackEmpty(ps));
  ps->top--;
}

察看栈顶的元素

StackTypeDate StackTop(Stack* ps)
{
  assert(ps);
  assert(!StackEmpty(ps));
  //注意这里的减一
  return ps->arr[ps->top-1];
}

栈的个数

int StackSize(Stack* ps)
{
  assert(ps);
  return ps->top;
}

栈是否为空

bool StackEmpty(Stack* ps)
{
  assert(ps);
  return ps->capacity == 0;
}

栈的销毁

void StackDestroy(Stack* ps)
{
  assert(ps);
  free(ps->arr);
  ps->arr = NULL;
  ps->capacity = ps->top = 0;
}
相关文章
|
1月前
|
算法 C语言
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
|
8天前
|
存储 前端开发 DataX
【数据结构】栈和队列
数据结构中的栈和队列
12 1
【数据结构】栈和队列
|
1天前
|
测试技术 编译器
栈溢出处理
栈溢出处理
|
8天前
【数据结构OJ题】用栈实现队列
力扣题目——用栈实现队列
18 0
【数据结构OJ题】用栈实现队列
|
8天前
【数据结构OJ题】用队列实现栈
力扣题目——用队列实现栈
20 0
【数据结构OJ题】用队列实现栈
|
26天前
|
存储 缓存 算法
堆和栈的区别及应用场景
堆和栈的区别及应用场景
|
1月前
|
存储 测试技术
【数据结构】操作受限的线性表,栈的具体实现
【数据结构】操作受限的线性表,栈的具体实现
32 5
|
1月前
|
算法 C语言
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
|
1月前
|
算法
【C/数据结构和算法】:栈和队列
【C/数据结构和算法】:栈和队列
33 1
|
21天前
|
API
用栈翻转字符串
用栈翻转字符串
15 0