Problem overview
A stack is a pile where you only touch the top. The last value pushed is the first one popped (last in, first out). The task is to write a class MyStack that stores int values in a private List<Integer> data = new ArrayList<>() and has four methods:
push(int value)puts a value on top and returns nothing.pop()removes the top value and returns it.peek()returns the top value and leaves it in place.size()returns how many values are stored.
The tests never call pop or peek on an empty stack. The driver pushes 10, 20 and 30, peeks, pops all three values, pushes 7 and peeks again. The output shows last in, first out:
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
Approach: the end of the list is the top
An ArrayList is cheap to grow and shrink at its end, so the end of the list is the top of the stack. push appends. peek reads the last element, and pop reads it and then removes it. After pushing 10, 20 and 30, the list holds [10, 20, 30] and the top, 30, is at the last index, which is data.size() - 1.
The one subtle point is pop, because it has two jobs: give the value back and take it off. Removing it first would lose the value, so the method saves it in a local variable, removes the element, and then returns the saved value.
Step by step
- Declare the class
MyStack. The driver'snew MyStack()builds objects from it. - Add the private field
data, aList<Integer>that starts as an emptyArrayList. Only the stack's own methods touch it. - Declare
pushas a publicvoidmethod taking anint value. - Append the value to the end with
data.add(value). - Declare
popas a public method returningint. Its body will have three lines. - Save the top in an
intnamedtop, read withdata.getat the last index. - Remove the last item with
data.removeand the same index. - Return
top, the value the caller asked for. - Declare
peekas a public method returningint. - Return the last item of
datawithout removing it. - Declare
sizeas a public method returningint. - Return
data.size(): one list item per stored value.
The solution in Java
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();
}
}
class Solution {
public void mainFunction() {
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());
}
}
Java details worth knowing:
- Imports.
ListandArrayListlive injava.util. In a standalone Java file you addimport java.util.*;at the top. - Boxing. The list holds
Integerobjects, while the methods useint. Java converts automatically:data.add(value)boxes theint, andint top = data.get(...)unboxes theInteger. remove(int)againstremove(Object).Listhas tworemovemethods, and with aList<Integer>the argument's type picks one. Anintexpression, likedata.size() - 1, removes by position. For[10, 20, 30],data.remove(Integer.valueOf(10))removes the value 10 and leaves[20, 30], whiledata.remove(1)on the resulting[20, 30]removes the item at position 1 and leaves[20]. Inpopthe argument is an index, which is what is needed.- Why
popsaves first. Afterdata.remove(...), the element is gone from the list. The localtopkeeps the value alive until thereturn. - The empty stack.
data.get(data.size() - 1)on an empty list asks for index -1 and throwsIndexOutOfBoundsExceptionwith the messageIndex -1 out of bounds for length 0. The lesson doesn't ask you to handle that case.
Complexity
Time: push appends in amortized O(1): the list occasionally grows its internal array, but averaged over many pushes each one costs a constant. peek, size and pop are O(1), because reading or removing the last element of an ArrayList shifts nothing.
Space: O(n) for n stored values.
Using the front of the list as the top would make push and pop O(n), because every other element would shift by one position.
Tracing the driver
The driver's output follows from the list: after the three pushes the list holds [10, 20, 30], so peek() prints 30 and size() prints 3. The first pop() prints 30 and leaves two items, then the next two pops print 20 and 10, so the size is 0. The stack is empty but still usable: push(7) makes it [7], so peek() prints 7 and size() prints 1.
Edge cases and common mistakes
- Returning before removing. A
return data.get(...)line ends the method, so theremovebelow it never runs. The size would never shrink. - Removing without saving. If
popremoves first and then reads the last index, it returns the wrong element, and on a one-element stack it fails. - Using the wrong index. With three values the top is at index 2, not 3.
data.get(data.size())throws. - Making the stack reusable. After popping everything, the stack has size 0 and accepts pushes again: after pushing 7,
peek()returns 7 andsize()returns 1. - Making
datapublic. Outside code could then add or remove items in the middle, which a stack must not allow.
