stack.h
#pragma once #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #include<assert.h> typedef int STDataType; typedef struct Stack { STDataType* arr; int top;//栈顶 int capacity; }ST; //用数组来实现栈 void STInit(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 STInit(ST* pst) { assert(pst); pst->top = 0; pst->capacity = 0; pst->arr = NULL; } void STDestroy(ST* pst) { assert(pst); free(pst->arr); pst->arr = NULL; pst->top = pst->capacity = 0; } void STPush(ST* pst, STDataType x) { assert(pst); // if (pst->top == pst->capacity) { int newcapacity = pst->capacity == 0 ? 4 : 2 * pst->capacity; STDataType* tmp = (STDataType*)realloc(pst->arr, newcapacity * sizeof(STDataType)); if (tmp == NULL) { perror("realloc:fail"); return; } pst->arr = tmp; pst->capacity = newcapacity; } pst->arr[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->arr[pst->top - 1]; } bool STEmpty(ST* pst) { assert(pst); if (pst->top == 0) { return true; } else return false; } int STSize(ST* pst) { assert(pst); return pst->top; }
test.c
#include"Stack.h" void test01() { ST st; STInit(&st); STPush(&st, 1); STPush(&st, 2); STPop(&st); STPop(&st); STPop(&st); while (!STEmpty(&st)) { printf("%d ", STTop(&st)); STPop(&st); } } int main() { test01(); }
栈的数组实现
最新推荐文章于 2024-05-28 12:11:29 发布