Stack follows LIFO ie., Last In First Out. In this data structure the elements are arranged in such a way that the last element added will be the first one to pop out of it.
Let’s implement this Stack data structure using ArrayList. We will implement the following APIs.
- push – To push the elements(Objects) into the Stack.
- pop – To pop the top Object from the Stack
- peek – To view the Top Object . This will not modify the Stack.
- size – Get the size of the Stack
- isEmpty – to check if the Stack is empty or not.
For our example, we will create a String Stack which will have String Objects.
package com.java.datastructure;
import java.util.ArrayList;
import java.util.List;
public class Stack {
@Override
public String toString() {
return "Stack [elements=" + elements + "]";
}
private List<String> elements = new ArrayList<>();
public String peek() {
if (elements.isEmpty()) {
return null;
}
return elements.get(elements.size() - 1);
}
public String pop() {
if (elements.isEmpty()) {
return null;
}
String top = elements.get(elements.size() - 1);
elements.remove(elements.size() - 1);
return top;
}
public void push(String element) {
elements.add(element);
}
public int size() {
return elements.size();
}
public boolean isEmpty() {
return elements.isEmpty();
}
public static void main(String[] args) {
Stack stack = new Stack();
System.out.println("Is Stack Empty:"+stack.isEmpty());
stack.push("Gyan");
stack.push("Vivek");
stack.push("Rochit");
stack.push("Panda");
System.out.println("Is Stack Empty:"+stack.isEmpty());
System.out.println(stack);
System.out.println("Stack Size:"+stack.size());
System.out.println("Peek Top Element:"+stack.peek());
System.out.println("After peek:"+stack);
System.out.println("Pop Top Element:"+stack.pop());
System.out.println("After pop:"+stack);
System.out.println("Stack Size now:"+stack.size());
}
}
Is Stack Empty:true
Is Stack Empty:false
Stack [elements=[Gyan, Vivek, Rochit, Panda]]
Stack Size:4
Peek Top Element:Panda
After peek:Stack [elements=[Gyan, Vivek, Rochit, Panda]]
Pop Top Element:Panda
After pop:Stack [elements=[Gyan, Vivek, Rochit]]
Stack Size now:3
Related Articles
Java Programs Asked in Interviews
Implement Custom Doubly Linked List in Java
Recommended Book: Data Structures and Algorithms Made Easy in Java