公司动态

栈结构实现与操作详解

📅 2026/7/24 21:12:10
栈结构实现与操作详解
栈只允许在栈的固定一端添加删除元素此端称之为栈顶另一端称之为栈底遵循后进先出原则。压栈:栈的插入操作。出栈栈的删除操作出数据也在栈顶。代码实现创建三个文件Stack.h用于接口声明Stack.c用于实现各个接口的函数Test.c用于测试各个接口Stack.h#pragma once #includestdio.h #includestdlib.h #includeassert.h #includestdbool.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#includeStack.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-top0); 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#includeStack.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; }