// Stack in C language #include #include #include "person.h" // use person from before #define STACK_SIZE 100 // constant for array size #define EMPTY_TOS -1 // top-of-stack starts at -1 struct stack{ // data structure is encapsulated into struct int top; // stack has a top person_ptr stack_array[STACK_SIZE]; // and an array of person ptrs }; typedef struct stack *stack_ptr; // stack accessed via this ptr int isEmpty(stack_ptr s) { // function returns "boolean" return(s->top == EMPTY_TOS); } int isFull(stack_ptr s) { // stack is full if all elements used return(s->top == STACK_SIZE-1); } void push(stack_ptr s, person_ptr p) { // give stack ptr, and person ptr if (!isFull(s)) // use s to tell if full s->stack_array[++s->top] = p; // s-> allows us to examine array and top } // pre-increment the top, and then add ptr person_ptr pop(stack_ptr s) { // return a ptr that is on top of stack if (isEmpty(s)) // return default if empty return NULL; else return(s->stack_array[s->top--]); // access the top, then post-decrement } stack_ptr stackConstructor() { // artificial C constructor stack_ptr s; s = (stack_ptr) malloc(sizeof(struct stack)); // allocate storage s->top = EMPTY_TOS; // initialize top field return(s); } void stackDestructor(stack_ptr s) { // artificial C deconstructor while (!isEmpty(s)) // iterate through all ptrs personDestructor(pop(s)); // memory leak - all persons have been popped already in main free(s); } int main(int argc, char *argv[]) { stack_ptr s = stackConstructor(); // allocate memory push(s, personConstructor("Name 1",10)); // push 3 persons onto stack push(s, personConstructor("Name 2",20)); // note its push(ptr,person) push(s, personConstructor("Name 3",30)); // Opposite of OO: obj.push(person) while (!isEmpty(s)) // pop 3 persons in opposite order printf("%s\n",toString(pop(s))); }