栈结构实现与操作详解
2026/7/24 21:12:05 网站建设 项目流程

栈:只允许在栈的固定一端添加删除元素,此端称之为栈顶,另一端称之为栈底,遵循后进先出原则。

压栈:栈的插入操作。

出栈:栈的删除操作,出数据也在栈顶。

代码实现

创建三个文件

Stack.h用于接口声明

Stack.c用于实现各个接口的函数

Test.c用于测试各个接口

Stack.h

#pragma once #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<stdbool.h> typedef int STDataType; typedef struct Stack { STDataType* a; int top; int capacity; }ST; //初始化和销毁 void STInite(ST* pst); void STDestroy(ST* pst); //进栈出栈 void STPush(ST* pst,STDataType x); void STPop(ST* pst); //取栈顶 STDataType STTop(ST* pst); //判空 bool STEmpty(ST* pst); //获取数据个数 int STSize(ST* pst);

Stack.c

#include"Stack.h" //初始化和销毁 void STInite(ST* pst) { assert(pst); pst->a = NULL; pst->capacity = 0; //指向栈顶元素下一位 pst->top = 0; //指向栈顶元素 //pst->top=-1; } void STDestroy(ST* pst) { assert(pst); free(pst->a); pst->a = NULL; pst->capacity = pst->top = 0; } //进栈出栈 void STPush(ST* pst,STDataType x) { assert(pst); //扩容 if (pst->top == pst->capacity) { int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2; STDataType* tmp = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType)); if (tmp == NULL) { perror("realloc fail"); exit(1); } pst->a = tmp; pst->capacity = newcapacity; } pst->a[pst->top] = x; pst->top++; } 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; } //获取数据个数 int STSize(ST* pst) { assert(pst); return pst->top; }

Test.c

#include"Stack.h" void test01() { //入栈:1 2 3 4 ST s; STInite(&s); STPush(&s, 1); STPush(&s, 2); STPush(&s, 3); STPush(&s, 4); while (!STEmpty(&s)) { printf("%d ", STTop(&s)); STPop(&s); } STDestroy(&s); } int main() { test01(); return 0; }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询