赞
踩
- #pragma once
- #include<stdio.h>
- #include<assert.h>
- #include<stdlib.h>
- #include<stdbool.h>
-
-
- typedef int STDataType;
- // 支持动态增长的栈
- typedef struct Stack
- {
- int* a;
- 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);

注意:
解决方法一:
解决方法二:
这里我们采用方法二
- #include"Stack.h"
-
- void STInit(ST* pst)
- {
- assert(pst);
-
- pst->a = NULL;
- pst->capacity = 0;
- pst->top = 0;
- }
-
- void STDestroy(ST* pst)
- {
-
- }
-
- // 栈顶插入删除
- 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, sizeof(STDataType) * newcapacity);
- if (tmp == NULL)
- {
- perror("realloc fail");
- return;
- }
-
- 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);
- int STSize(ST* pst);

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。