Start learning free

LESSON 407 OF 410 · PROJECTS: OBJECT-ORIENTED

Stack: Build a MyStack Class (Java) in Java

Practice

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a private List<Integer> data = new ArrayList<>() and offers four operations.

The methods:

  • public void push(int value)
  • public int pop()
  • public int peek()
  • public int size()

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In Java, get on an empty list throws an IndexOutOfBoundsException.)

You start with: The starter already contains the code that uses your stack (below).

MyStack s = new MyStack();
s.push(10);
s.push(20);
s.push(30);
System.out.println("Top: " + s.peek());
System.out.println("Size: " + s.size());
System.out.println("Pop: " + s.pop());
System.out.println("Size: " + s.size());
System.out.println("Pop: " + s.pop());
System.out.println("Pop: " + s.pop());
System.out.println("Empty size: " + s.size());
s.push(7);
System.out.println("Top: " + s.peek());
System.out.println("Size: " + s.size());

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

ArrayList has add, get(index) and remove(index); the last index is data.size() - 1. pop must return the old top, so save it in a variable before calling remove, then return the variable.

class MyStack {
    private List<Integer> data = new ArrayList<>();

    public void push(int value) {
        data.add(value);
    }

    public int pop() {
        int top = data.get(data.size() - 1);
        data.remove(data.size() - 1);
        return top;
    }

    public int peek() {
        return data.get(data.size() - 1);
    }

    public int size() {
        return data.size();
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    Stack Impl in Java

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free