CSC 161 | Grinnell College | Spring, 2009 |
Imperative Problem Solving and Data Structures | ||
This laboratory exercise provides practice with an array implementation of the Stack Abstract Data Type.
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; }
Complete the implementation of a stack of strings by implementing the remaining operations:
Declare and initialize three stacks (for bills, magazines, and notes) within your main program. Then test your code, including the following:
Expand the code for the stack ADT implementation by adding these procedures:
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.)
This document is available on the World Wide Web as
http://www.walker.cs.grinnell.edu/courses/161.sp09/labs/lab-stacks-arrays.shtml
created 28 April 1997 last revised 13 April 2009 |
![]() ![]() |
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu. |