栈是一种先进后出(LIFO)的线性表,栈规定只能在栈的尾部插入和删除元素;
#include#define INISTACKSIZE 20 #define STACKINCREMENT 10 typedef int ElemType; typedef struct { ElemType *base; //栈低指针 ElemType *top; //栈顶指针 int stackSize; //栈的存储空间大小,栈当前的最大容量 }sqStack; void InitStack(sqStack *s) { std::cout << "ini buffern"; s->base = (ElemType*)malloc(INISTACKSIZE * sizeof(ElemType)); if (!s->base) { exit(0); } s->top = s->base; s->stackSize = INISTACKSIZE; } void PushStack(sqStack *s, ElemType e) { if (s->top - s->base == s->stackSize) { std::cout << "new buffern"; s->base = (ElemType*)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType)); if (!s->base) { exit(0); } s->top = s->base + s->stackSize; //栈重新分配内存后,s->top 重指 s->stackSize += STACKINCREMENT; } *(s->top) = e; s->top++; } void PopStack(sqStack *s, ElemType *e) { if (s->top == s->base) { return; } s->top--; *e = *(s->top); } int GetElemNums(sqStack s) { return s.top - s.base; } int main() { sqStack s; InitStack(&s); for (int i = 0; i < 51; i++) { ElemType e = i; PushStack(&s, e); } int cout = GetElemNums(s); std::cout << "n" < ElemType e = i; PopStack(&s, &e); std::cout << e << " "; } cout = GetElemNums(s); std::cout << "n" <



