Lab 09

Stacks and Queues

Objective

The goal of this lab is to gain experience with stack and queue data structures and their applications.

Introduction

In this lab, you will use stacks and queues to solve problems. To facilitate development, we will provide a dynamic array implementation of the Stack and Queue ADTs.

Download the lab starter files here:

Don’t forget to download and customize your machine-specific makefile.

In addition, you may find the following functions from ctype.h useful in this lab:

Part 1: Using Stacks and Queues

Write some code in the main method to accomplish the following tasks:

  1. Allocate and initialize a stack and queue. You may store these structures on either the stack or the heap, but make sure you free them appropriately.

  2. Add the letters ‘a’, ‘b’, ‘c’, and ’d’ (in that order) to both the stack and the queue.

  3. Remove all items from the stack until it is empty and print them in the order that they are returned.

  4. Remove all items from the queue until it is empty and print them in the order that they are returned.

Compare the results from #3 and #4; how are they different?

Part 2: Palindromes

Use a stack and queue to implement a more powerful version of the is_palindrome() function from an earlier lab. As a reminder, this function implements simple palindome verification. Here is the signature and documentation for the function:

For this lab, you should make the function more flexible than the version you wrote for the earlier lab. Your new solution should ignore whitespace and punctuation, and all comparisons should be case-insensitive. Include some tests in your main function. Examples of valid palindromes:

Part 3: Postfix Evaluation

Postfix notation (sometimes called “Reverse Polish Notation” or “RPN”) explicitly specifyies the operation order of a mathematical expression. Here are some examples of normal (infix) expressions followed by their postfix equivalents:

Here is an algorithm for evaluating simple postfix expressions using a stack:

for each token in expression
    if token is a number
        push(token)
    if token is an operator <op>
        op2 = pop()
        op1 = pop()
        push(op1 <op> op2)
return pop()

Implement this algorithm for simple expressions (single-digit numbers only) by writing a function with the following signature:

HINT: You can convert a character c to its integer equivalent value using the following expression:

(int)(c-'0')

Include some tests in a main() function. Examples:

(Optional) Challenge Problem

Modify your eval_postfix function so that it works for multi-digit character literals.

HINT: You may wish to use the strtok function to split up the string around spaces, and the atoi function to convert strings to integers.