Data Structure --- c language for Stack sequential storage, data structure --- c
// Stack sequential storage // Yang Xin # include <stdio. h> # include <stdlib. h> // define the stack size # define STACK_INIT_SIZE 10 # define STACKINCREMENT 2 // define the function return value Status typedef int Status; # define TRUE 1 # define FALSE 0 # define OK 1 # define ERROR 1 # define INFEASIBLE-1 # define OVERFLOW-2 // define the struct typedef int SElemType; typedef struct SqStack {SElemType * base; // stack bottom SElemType * top; // stack top int stacksize; // stack size} SqStack; // stack initialization Status init_Stack (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;} // stack destruction Status destory_Stack (SqStack * S) {free (* S ). base); (* S ). base = NULL; (* S ). top = NULL; (* S ). stacksize = 0; return OK;} // clear Status clear_Stack (SqStack * S) {(* S ). top = (* S ). base; return OK;} // determines whether the stack is empty. Status isempty_Stack (SqStack S) {if (S. top = S. base) return TRUE; elsereturn FALSE;} int length_Stack (SqStack S) {return S. top-S. base;} // return the top stack element Status get_Top (SqStack S, SElemType * e) {if (S. top> S. base) {* e = * (S. top-1); return OK;} elsereturn ERROR;} // push (SqStack * S, SElemType e) {if (* S ). top-(* S ). base> = (* S ). stacksize) {(* S ). base = (SElemType *) realloc (* S ). base, (* S ). stacksize + STACKINCREMENT) * sizeof (SElemType); if (! (* S ). base) exit (OVERFLOW); (* S ). top = (* S ). base + (* S ). stacksize; (* S ). stacksize + = STACKINCREMENT;} * (* S ). top) ++ = e; return OK;} // output stack Status pop (SqStack * S, SElemType * e) {if (* S ). top = (* S ). base) return ERROR; * e = * -- (* S ). top; return OK;} // traverse the stack element Status traverse_Stack (SqStack S) {while (S. top> S. base) {printf ("% d", * S. base ++);} printf ("\ n"); return OK;} int main () {int j; SqStack s; SElemType e; if (init_Stack (& s) = OK) for (j = 1; j <= 12; j ++) push (& s, j); printf ("the elements in the stack are: \ n "); traverse_Stack (s); pop (& s, & e); printf (" pop-up top stack Element e = % d \ n ", e ); printf ("Stack null No: % d (1: NULL 0: No) \ n", isempty_Stack (s); get_Top (s, & e ); printf ("Stack top Element e = % d stack length: % d \ n", e, length_Stack (s); clear_Stack (& s ); printf ("Empty Stack: % d (1: Empty 0: No) \ n", isempty_Stack (s); destory_Stack (& s ); printf ("after the stack is destroyed, s. top = % u s. base = % u s. stacksize = % d \ n ", s. top, s. base, s. stacksize); return 0 ;}