动态顺序栈

简介: 动态顺序栈

一、顺序栈的结构定义

//顺序栈的结构定义
typedef int STDataType;
typedef struct Stack {
  STDataType* a;
  int top;
  int capacity;
}ST;

二、顺序栈的初始化

//顺序栈的初始化
void STInit(ST* pst)
{
  assert(pst);
  pst->a = NULL;
  pst->top = 0;//top指针指向栈顶元素的下一位
  pst->capacity = 0;//顺序栈的容量
}

三、顺序栈的打印

//顺序栈的打印
void STPrint(ST pst)
{
  for (int i = 0; i < pst.top; i++)
  {
    printf("%d ", pst.a[i]);
  }
  printf("\n");
}

四、顺序栈的入栈

//顺序栈的入栈
void STPush(ST* pst, STDataType x)
{
  assert(pst);
  //检查扩容
  if (pst->top == pst->capacity)
  {
    int newcapacity = pst->capacity == 0 ? 4 : 2 * pst->capacity;
    STDataType* p = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType));
    if (p == NULL)
    {
      perror("realloc fail");
      exit(-1);
    }
    else
    {
      pst->a = p;
      pst->capacity = newcapacity;
    }
  }
  pst->a[pst->top++] = x;
}

五、顺序栈的出栈

//顺序栈出栈
void STPop(ST* pst)
{
  assert(pst);
  assert(pst->top > 0);
  pst->top--;
}

六、求顺序栈栈顶元素

//求顺序栈栈顶元素
STDataType STTop(ST* pst)
{
  assert(pst);
  assert(pst->top > 0);
  return pst->a[pst->top - 1];
}

七、顺序栈判空

//顺序栈判空
bool STEmpty(ST* pst)
{
  assert(pst);
  return pst->top == 0;
}

八、顺序栈销毁

//顺序栈销毁
void STDestroy(ST* pst)
{
  assert(pst);
  if (pst->a != NULL)
  {
    free(pst->a);
    pst->a = NULL;
    pst->top = 0;
    pst->capacity = 0;
  }
}

九、测试代码

void test01()
{
    //定义顺序栈
    ST st;
    //初始化顺序栈
    STInit(&st);
    //顺序栈入栈
    STPush(&st, 1);
    STPush(&st, 2);
    STPush(&st, 3);
    STPush(&st, 4);
    STPush(&st, 5);
    //顺序栈打印
    STPrint(st);
    //顺序栈出栈
    STPop(&st);
    STPop(&st);
    STPop(&st);
    //顺序栈打印
    STPrint(st);
    //打印栈顶元素
    printf("%d\n", STTop(&st));
    //顺序栈判空
    if (STEmpty(&st))
        printf("空\n");
    else
        printf("非空\n");
    //顺序栈出栈
    STPop(&st);
    STPop(&st);
    //顺序栈判空
    if (STEmpty(&st))
        printf("空\n");
    else
        printf("非空\n");
    //顺序栈销毁
    STDestroy(&st);
}
int main()
{
    test01();
    return 0;
}


目录
相关文章
|
3天前
|
算法 C语言
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
|
3天前
|
存储 测试技术
【数据结构】操作受限的线性表,栈的具体实现
【数据结构】操作受限的线性表,栈的具体实现
16 5
|
3天前
|
算法 C语言
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
|
4天前
|
算法
【C/数据结构和算法】:栈和队列
【C/数据结构和算法】:栈和队列
13 1
|
8天前
|
C++
【洛谷 P1044】[NOIP2003 普及组] 栈 题解(递归+记忆化搜索)
**NOIP2003普及组栈问题**:给定操作数序列1到n,仅允许push(进栈)和pop(出栈)操作。目标是计算所有可能的输出序列总数。输入包含一个整数n(1≤n≤18)。示例输入3,输出5。当队列空时返回1,栈空则只能入栈,栈非空时可入栈或出栈。AC C++代码利用记忆化搜索求解。
9 1
|
10天前
|
算法
$停车场管理系统 栈与队列
$停车场管理系统 栈与队列
8 1
|
14天前
数据结构 栈 / 队列(第9天)
数据结构 栈 / 队列(第9天)
|
1天前
|
存储 人工智能 程序员
技术心得记录:堆(heap)与栈(stack)的区别
技术心得记录:堆(heap)与栈(stack)的区别
|
3天前
【海贼王的数据航海】栈和队列
【海贼王的数据航海】栈和队列
4 0
|
3天前
|
存储 算法 编译器
【数据结构与算法】使用数组实现栈:原理、步骤与应用
【数据结构与算法】使用数组实现栈:原理、步骤与应用