#include<stdio.h> #include<stdlib.h> #define ok 1 #define error 0 #define overflow -2 typedef struct { int *base,*top; int stacksize; }sqstack; int initstack(sqstack *s) { S -> Base = ( int *) the malloc ( 10 * the sizeof ( int )); // advance of s-> base points 10 memory space allocation storage type int IF (S->! Base ) return overflow ; s->top=s->base; s->stacksize=10; return ok; } int gettop(sqstack *s,int *e) { if(s->top==s->base)return error; *e=*(s->top-1); return ok; } int pop(sqstack *s,int *e) { if(s->top==s->base)return error; *e=*--s->top; return ok; } int push(sqstack *s,int e) { if(s->top-s->base>=s->stacksize) { S -> Base = ( int *) realloc (S-> Base , (S-> STACKSIZE + 10 ) * the sizeof ( int )); // If the stack is full, to again s-> base points to memory space allocation 10 storage type int IF (S->! Base ) return overflow; s->top=s->base+s->stacksize; s->stacksize++; } *s->top++=e; return ok; } void main() { sqstack *s; int i,j; initstack(&s); push(&s,1); push(&s,2); push(&s,3); push(&s,4); push(&s,5); push(&s,6); push(&s,7); push(&s,8); push(&s,9); push(&s,10); push(&s,11); push(&s,12); push(&s,13); push(&s,14); push(&s,15); i=gettop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); i=pop(&s,&j); printf("i=%d,j=%d\n",i,j); }
Test function defines four functions: initstack configured to obtain a top element empty stack gettop push element is inserted into a pop pop the top element
Program results are as follows:
I represents the value of pop, gettop return value can be found in the last three i is 0, indicating an empty stack, the value of j has not changed. Before the values can be output correctly.