Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 4 – Stacks

Part 1 – A stack on top of a list

Task 1 – The Stack ADT and its implementation

Create StackADT.java:

interface StackADT<E> {
    void push(E x);
    E pop();
    E top();
    boolean isEmpty();
}

Then write Stack<E> using your LinkedList<E> from Lab 3: the head of the list is the top of the stack, so push is addFront and pop is getHead followed by removeFront. All operations are O(1)O(1).

class Stack<E> implements StackADT<E> {
    private List<E> list;
    // ToDo
}
Solution
class Stack<E> implements StackADT<E> {
    private List<E> list;

    public Stack() {
        list = new LinkedList<E>();
    }
    public boolean isEmpty() {
        return list.empty();
    }
    public void push(E x) {
        list.addFront(x);               // the head of the list is the top
    }
    public E pop() {
        E x = list.getHead();
        list.removeFront();
        return x;
    }
    public E top() {
        return list.getHead();
    }
}

Task 2 – Balanced symbols

Check whether the brackets (), [], {} of an expression are balanced: push every opening symbol; a closing symbol must match the popped one; the stack must be empty at the end.

static boolean checkBalance(String expr) {
    // ToDo
}
Solution
static boolean checkBalance(String expr) {
    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < expr.length(); i++) {
        char x = expr.charAt(i);
        if (x == '(' || x == '[' || x == '{')
            stack.push(x);
        else if (x == ')' || x == ']' || x == '}') {
            if (stack.isEmpty())
                return false;             // nothing to close
            char open = stack.pop();
            if ((x == ')' && open != '(') || (x == ']' && open != '[')
                    || (x == '}' && open != '{'))
                return false;             // wrong kind of bracket
        }
    }
    return stack.isEmpty();               // everything closed?
}

Task 3 – Evaluate a postfix expression

The tokens are separated by spaces: "6 5 2 3 + 8 * + 3 + *". Push numbers; for an operator, pop two numbers, apply it, push the result.

🚩 The first number popped is the right operand: 8 2 - is 8−28 - 2.

static int evalPostfix(String expr) {
    // ToDo   (use expr.split(" ") and Integer.parseInt)
}
Solution
static int evalPostfix(String expr) {
    Stack<Integer> s = new Stack<>();
    for (String tok : expr.split(" ")) {
        if (tok.length() == 1 && "+-*/".contains(tok)) {
            int right = s.pop();          // popped first = right operand
            int left = s.pop();
            switch (tok) {
                case "+": s.push(left + right); break;
                case "-": s.push(left - right); break;
                case "*": s.push(left * right); break;
                default:  s.push(left / right);
            }
        } else {
            s.push(Integer.parseInt(tok));
        }
    }
    return s.pop();
}

Task 4 – Convert infix to postfix

Operands (letters or digits) go to the output. ( is pushed; ) pops until (. An operator first pops the operators of higher or equal precedence (stopping at (), then is pushed. At the end, pop everything.

static String infixToPostfix(String expr) {
    // ToDo   (put a space after each output symbol)
}
Solution
static int prec(char op) {
    return (op == '*' || op == '/') ? 2 : 1;          // + and - : 1
}

static String infixToPostfix(String expr) {
    Stack<Character> ops = new Stack<>();
    StringBuilder out = new StringBuilder();
    for (char c : expr.toCharArray()) {
        if (Character.isLetterOrDigit(c)) {
            out.append(c).append(' ');                // operand: output
        } else if (c == '(') {
            ops.push(c);
        } else if (c == ')') {
            while (ops.top() != '(')
                out.append(ops.pop()).append(' ');
            ops.pop();                                // discard the '('
        } else if ("+-*/".indexOf(c) >= 0) {
            while (!ops.isEmpty() && ops.top() != '(' && prec(ops.top()) >= prec(c))
                out.append(ops.pop()).append(' ');
            ops.push(c);
        }                                             // spaces are ignored
    }
    while (!ops.isEmpty())
        out.append(ops.pop()).append(' ');
    return out.toString().trim();
}

Test your stack

Stack<Integer> s = new Stack<>();
for (int i = 1; i <= 4; i++)
    s.push(i * 10);
System.out.println(s.pop() + " " + s.pop() + " " + s.top() + " " + s.isEmpty());

String[] exprs = {"A*(B+C)*D+E[I]", "A*(B+C*D+E[I]", "A*(B+E[I)+C]*D", "{[()()]}"};
for (String e : exprs)
    System.out.println(e + " -> " + checkBalance(e));

String[] post = {"6 5 2 3 + 8 * + 3 + *", "5 1 2 + 4 * + 3 -", "8 2 - 3 /"};
for (String p : post)
    System.out.println(p + " = " + evalPostfix(p));

String[] infix = {"A*B+C*D", "A+B*C+(D*E+F)*G", "a/b*(c+(d-e))",
                  "((a*b)-(c*d)/2-(e*f))/g"};
for (String in : infix)
    System.out.println(in + " -> " + infixToPostfix(in));

Expected output:

40 30 20 false
A*(B+C)*D+E[I] -> true
A*(B+C*D+E[I] -> false
A*(B+E[I)+C]*D -> false
{[()()]} -> true
6 5 2 3 + 8 * + 3 + * = 288
5 1 2 + 4 * + 3 - = 14
8 2 - 3 / = 2
A*B+C*D -> A B * C D * +
A+B*C+(D*E+F)*G -> A B C * + D E * F + G * +
a/b*(c+(d-e)) -> a b / c d e - + *
((a*b)-(c*d)/2-(e*f))/g -> a b * c d * 2 / - e f * - g /

The last expression is the one of the 1444 final exam.

Part 2 – Use the JDK

Challenge 1 – The next greater element

For every element of an array, find the first larger element to its right (-1 if none), in O(n)O(n). Scan from right to left and keep on the stack only the elements that can still be “the next greater” of something: pop every element ≤\le the current one, read the top, push the current one.

Solution
static int[] nextGreater(int[] a) {
    int[] res = new int[a.length];
    Deque<Integer> st = new ArrayDeque<>();      // used as a stack
    for (int i = a.length - 1; i >= 0; i--) {
        while (!st.isEmpty() && st.peek() <= a[i])
            st.pop();                            // hidden behind a[i] for good
        res[i] = st.isEmpty() ? -1 : st.peek();
        st.push(a[i]);
    }
    return res;
}
System.out.println(Arrays.toString(nextGreater(new int[]{4, 5, 2, 25, 7, 8})));
System.out.println(Arrays.toString(nextGreater(new int[]{9, 7, 5, 3})));

Expected output:

[5, 25, 25, -1, 8, -1]
[-1, -1, -1, -1]

Challenge 2 – Undo and redo in a text editor

Every typed piece of text goes on an undo stack. undo() moves the last piece to a redo stack and removes it from the text; redo() does the opposite. Typing something new empties the redo stack.

Solution
static StringBuilder text = new StringBuilder();
static Deque<String> undo = new ArrayDeque<>();
static Deque<String> redo = new ArrayDeque<>();

static void type(String s) {
    text.append(s);
    undo.push(s);
    redo.clear();                    // a new action cancels the redo history
}
static void undo() {
    if (undo.isEmpty()) return;
    String s = undo.pop();
    text.setLength(text.length() - s.length());
    redo.push(s);
}
static void redo() {
    if (redo.isEmpty()) return;
    String s = redo.pop();
    text.append(s);
    undo.push(s);
}
type("Hello"); type(" big"); type(" world");
System.out.println(text);
undo(); undo();
System.out.println(text);
redo();
System.out.println(text);
type("!");
redo();                          // nothing to redo any more
System.out.println(text);

Expected output:

Hello big world
Hello
Hello big
Hello big!

Challenge 3 – A stack with min() in O(1)O(1)

Write a class MinStack with push, pop and min, all O(1)O(1). Use a second ArrayDeque whose top is always the current minimum.

Solution
static class MinStack {
    private Deque<Integer> s = new ArrayDeque<>();
    private Deque<Integer> mins = new ArrayDeque<>();   // top = current minimum

    void push(int x) {
        s.push(x);
        if (mins.isEmpty() || x <= mins.peek())
            mins.push(x);
    }
    int pop() {
        int x = s.pop();
        if (x == mins.peek())
            mins.pop();
        return x;
    }
    int min() {
        return mins.peek();
    }
}
MinStack m = new MinStack();
m.push(5); m.push(3); m.push(7); m.push(2);
System.out.println("min = " + m.min());
m.pop();
System.out.println("min = " + m.min());
m.pop(); m.pop();
System.out.println("min = " + m.min());

Expected output:

min = 2
min = 3
min = 5