CSC 161 Schedule Readings Labs & Projects Homework Deadlines Resources

Balancing Parentheses

Write a program that reads a line of text from the terminal and checks whether the parentheses in the line are balanced.

Notes

Examples

  1. ( these { parentheses[] match } perfectly ) !!!
  2. (the {right [parentheses ) on } this line ] are in the wrong order.
  3. this ( line { is missing } one (round ) right parenthesis.

Strategy

This problem can be solved reasonably easily using a single left-to-right scan of a line, if left parentheses are placed on a stack as they are encountered. Then, when a right parenthesis is found, the stack can be popped and one can check whether the right parenthesis has the same type as the left one.

Programming note

Your program should use a self-contained list-based stack library package, as developed in the lab on stacks.