/** * array-stack.c * An array-based implementation of stacks. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include // For malloc #include "linear.h" // Signatures of the methods we provide. // +-------+---------------------------------------------------------- // | Types | // +-------+ struct linear { char **contents; // Contents of the stack (an array of strings) int capacity; // Capacity of the stack int size; // Number of elements in the stack }; // +---------+-------------------------------------------------------- // | Helpers | // +---------+ // +----------------------------+------------------------------------- // | Constructors & Destructors | // +----------------------------+ struct linear * construct (int minimum_capacity) { // Allocate the enclosing structure struct linear *linear = (struct linear *) malloc (sizeof (struct linear)); if (linear == NULL) return NULL; // Allocate the array of strings linear->contents = calloc (minimum_capacity, sizeof (char *)); if (linear->contents == NULL) { free (linear); return NULL; } // Fill in the fields. (Note that calloc zeroes memory, so we don't // have to set things to 0.) linear->capacity = minimum_capacity; linear->size = 0; // And we're done return linear; } // construct void destruct (struct linear *linear) { free (linear->contents); linear->contents = NULL; free (linear); } // destruct // +-----------+------------------------------------------------------ // | Observers | // +-----------+ int is_empty (struct linear *linear) { return linear->size == 0; } // is_empty int is_full (struct linear *linear) { return linear->size == linear->capacity; } // is_full char * peek (struct linear *linear) { if (linear->size == 0) return NULL; return linear->contents[linear->size-1]; } // peek // +----------+------------------------------------------------------- // | Mutators | // +----------+ int add (struct linear *linear, char *str) { linear->contents[(linear->size)++] = str; return 1; } // add char * get (struct linear *linear) { return linear->contents[--(linear->size)]; } // get void clear (struct linear *linear) { linear->size = 0; } // clear