CSC 161 Grinnell College Spring, 2010
 
Imperative Problem Solving and Data Structures
 

Stacks with Arrays

Goals

This laboratory exercise provides practice with an array implementation of the Stack Abstract Data Type.

Stacks as ADTs

The reading describes a stack as an object that can store data and that has the following operations:

Within C, there is no way to combine underlying data structures (e.g., arrays) and operations within a single structure. (Such a combined ADT can be done in C++ or Java, but we leave those languages for other courses!) Instead, we will define variables for each stack needed. For each operation, we will pass the relevant variables as parameters, so we can use the same functions for multiple stacks. This approach requires that the data items for the stack have the same type (e.g., a stack of doubles or a stack of strings).

For this lab, we will focus on arrays of strings, and this leads to the following declarations for stacks of bills, magazines, and notes:

   #define MaxStack  50  /* MaxStack stands for the size of all stack arrays */

   typedef struct {
      int topPosition;
      char * stackArray [MaxStack];
   } stringStack;      /* type for a stack of strings */

With this framework, the full and push operations might be defined as follows:

   int full (stringStack stack) {
      /* determine if there are more positions in a stackArray */
      return (stack.topPosition == (MaxStack-1));
   }

   int push (stringStack *stack, char * item) {
      /* return -1 if stack full */
      if (full (*stack)) {
         printf ("attempt to push item onto an already full stack\n");
         return -1;
      }

      /* add item to stack */
      (stack->topPosition) ++;
      stack->stackArray[stack->topPosition] = item;
   }
  1. Complete the implementation of a stack of strings by implementing the remaining operations:

  2. Declare and initialize three stacks (for bills, magazines, and notes) within your main program. Then test your code, including the following:

  3. Expand the code for the stack ADT implementation by adding these procedures:

  4. The stack described by the push operation above just maintains a reference to a string that is passed into it. Revise the push operation so that it allocates space for a new string and copies the string parameter into this new space. (Thus, if the original string were changed later in the program, the string on the stack remains the same.)

Work to be turned in:


This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~walker/courses/161.sp10/labs/lab-stacks-arrays.shtml

created 28 April 1997
last revised 4 April 2010
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.