CS 241 Lab 4: Balancing Brackets with a Stack

With this lab, you’ll implement the balanced-bracket checking algorithm we discussed in lecture. But you’ll do so by first writing a Stack interface and then providing two implementations, one using arrays and one using linked lists.

Stacks in two styles

Write up the following interfaces and classes for stacks in Java, along with one project implementation (the bracket checker); you may use either implementation to test your project.

Finally, you should provide a short little project which checks for balanced brackets in a string, using a stack. The idea is that an input string (read in via GUI or command line) will contain a mixture of parentheses (round: "( )"), brackets (square: "[ ]") and braces (curly: "{ }"), and that your program should either validate that it contains only well-nested, well-sequenced pairs, or indicate what sort of error happens.

For example, on input "( ()[] { [] () } )" your program would respond that the brackets (in the general sense) are all balanced properly. But on input "( [ ] { ( } ) )" you would report a mis-match at the first closing (curly) brace, since it does not match the preceding open parenthesis. In general, there will be other characters besides brackets and spaces—just ignore them!

The Bracket-checking Algorithm

The basic algorithm for this lab was described in lecture; it goes something like this: