Daily Archives: May 14, 2012

C++ || Stack – Using A Stack, Determine If A Set Of Parentheses Is Well-Formed

Here is another homework assignment which was presented in a C++ Data Structures course. This assignment was used to introduce the stack ADT, and helped prepare our class for two later assignments which required using a stack. Those assignments can be found here:

(1) Stack Based Infix To Postfix Conversion (Single Digit)
(2) Stack Based Postfix Evaluation (Single Digit)

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Stack Data Structure
Cin.getline
#include "ClassStackListType.h"

A simple exercise for testing a stack is determining whether a set of parenthesis is “well formed” or not. What exactly is meant by that? In the case of a pair of parenthesis, for an expression to be well formed, consider the following table.

Given an expression with characters and parenthesis, ( ), [ ], and { }, our class was asked to determine if an expression was well formed or not by using the following algorithm:

======= WELL-FORMED EXPRESSIONS =======

This program uses a custom template.h class. To obtain the code for that class, click here.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: the code was compile four separate times to display different output)

====== RUN 1 ======

Enter an expression and press ENTER.
((
The expression: (( is NOT well formed!!!

====== RUN 2 ======

Enter an expression and press ENTER.
(a{b[]}c)

The expression: (a{b[]}c) is well formed...

====== RUN 3 ======

Enter an expression and press ENTER.
[(7 * 28) - 1987]

The expression: [(7 * 28) - 1987] is well formed...

====== RUN 4 ======

Enter an expression and press ENTER.
{3 + [2 / 3] - (9 + 18) * 12)

The expression: {3 + [2 / 3] - (9 + 18) * 12) is NOT well formed!!!