Balancing Parentheses

A stack is a good way to test whether parentheses are balanced. An open paren must be matched by a close paren of the same kind, and whatever is between the parens must be balanced. ({[][][]}) is balanced, but ({[) is not.


public class charStack {
    int n;
    char[] stack;
    public charStack()
        { n = 0;
          stack = new char[100]; }
    public void push(char c) {
        stack[n++] = c; }
    public char pop() {
        return stack[--n]; }
    public boolean empty() {
        return ( n == 0 ); }

This example illustrates that it is easy to roll your own stack.

Contents    Page-10    Prev    Next    Page+10    Index