Stacks and Queues

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Stacks and Queues

  • intentionally restrictive
  • limit where you can add and remove elements

Stacks: Last-In, First-Out (LIFO)

Queues: First-In, First-Out (FIFO)

Stacks

  • add to the top (push)
  • remove from the top (pop)

Queues

  • add to the back (enqueue)
  • remove from the front (dequeue)

Balanced Parentheses Checker

Problem: Write a program that checks if parentheses, brackets, and braces are properly balanced in a string.

Examples:

  • \(()\) → valid
  • \(()[]{}\) → valid
  • \(([{}])\) → valid
  • \((]\) → invalid
  • \(([)]\) → invalid
  • \((((\) → invalid

Node.java

public class Node {
    private char character;
    private Node next;

    public Node(char c) { character = c; }

    public char getChar() { return character; }

    public void setChar(char c) { character = c;}

    public Node getNext() { return next; }

    public void setNext(Node node) { next = node; }
}

Stack.java

public class Stack {
    private Node head;

    public void push(char c) {
        // to implement
    }

    public char pop() {
        // to implement
    }

    public boolean isEmpty() {
        // to implement
    }

}

BalancedParentheses.java

public class BalancedParentheses {

    // Test cases
    public static void main(String[] args) {
        String[] testCases = {
                "()",           // true
                "()[]{}",       // true
                "()[]{}",     // true
                "([{}])",       // true
                "([{}])",     // true
                "(]",           // false
                "([)]",         // false
                "(((",          // false
                "",             // true (empty string is balanced)
                "({[]})",       // true
                "((())",        // false
                "hello(world)", // true (ignores non-bracket chars)
                ")(",           // false
                "[(])"          // false
        };

        System.out.println("Testing Balanced Parentheses Checker:\n");
        for (String test : testCases) {
            boolean result = isBalanced(test);
            System.out.printf("'%s' -> %s%n", test, result);
        }
    }

    public static boolean isBalanced(String test) {
        // to implement
    }

    private static boolean isOpenParentheses(char c) {
        return c == '(' || c == '[' || c == '{';
    }

    private static boolean isCloseParentheses(char c) {
        return c == ')' || c == ']' || c == '}';
    }

    private static boolean isAMatch(char open, char close) {
        return (int) (close - open) < 3 && (int) (close - open) > 0;
    }

}