#include <stdio.h> #include <stdlib.h> #define STACK_INIT_SIZE 100 #define STACK_INCREMENT 10 #define OK 1 #define ERROR 0 #define OVERFLOW -1 typedef int status; typedef int SElemType; typedef struct { SElemType *base;//在构造之前和销毁之后,base的值为NULL SElemType *top;//栈顶指针 int stacksize;//当前分配的存储空间,以元素为单位 }SqStack; //构造一个空栈 status InitStack(SqStack &S) { S.base = (SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType)); if(!S.base)exit(OVERFLOW); S.top = S.base; S.stacksize = STACK_INIT_SIZE; return OK; } //输出栈顶元素 status GetTop(SqStack &S, SElemType &e) { if(S.top == S.base) return ERROR; e = *(S.top-1); return OK; } //元素入栈 status Push(SqStack &S, SElemType e) { if(S.top - S.base >= S.stacksize) { S.base =(SElemType*)realloc(S.base, (S.stacksize + STACK_INCREMENT)*sizeof(SElemType)); if(!S.base) exit(OVERFLOW); S.top = S.base+S.stacksize; S.stacksize = S.stacksize + STACK_INCREMENT; } *S.top++ = e; return OK; } //元素出栈 status Pop(SqStack &S, SElemType &e) { if(S.top == S.base) return ERROR; e = *--S.top; return OK; } //*************测试程序***********************// int main() { SqStack s; int e; if(InitStack(s)) printf("Init succeed!\n"); if(Push(s, 4)) printf("Push succeed!\n"); if(Push(s, 2)) printf("Push succeed!\n"); if(GetTop(s, e)) printf("Get succeed!\n"); printf("%d\n", e); if(Pop(s,e)) printf("Pop succeed!\n"); printf("%d\n",e); return 0; }
时间: 2024-12-19 15:09:52