Stack Data Structure - The Coding Shala

Home >> Data Structures >> Stack

Stack Data Structure

In this post, we will see the basics of the stack data structure. The stack is Data Structure also known as Last-in-first-out(LIFO) data structure. In Stack, the newest element added to the stack will be processed first. Like Queue in stack two operations are important. One is inserted operation is called a stack. A new element is always added at the end of the stack. The delete operation is called pop, will always remove the last element.

The general operations we perform on the stack are below:
  • Push: Add an item to the stack. If the stack is full then return overflow.
  • Pop: Remove an element from the stack. If the stack is empty, then underflow.
  • Peek / Top: Return the top element of the stack.
  • isEmpty: Returns true if the stack is empty else false.
All operations push(), pop(), isEmpty(), peek() take O(1) time.

How to implement a stack?
There are two ways to implement a stack:
  • Using Array.
  • Using Linked List.

Stack Java Program Using ArrayList

The Following example explains the stack Implementation: 

import java.util.ArrayList;
import java.util.List;

//stack example

class Stack{
 private List<Integer> stack;
  stack = new ArrayList<Integer>();
 //add element
 public void push(int val) {
 //remove element from top
 public void pop() {
  if(!isEmpty()) stack.remove(stack.size()-1);
 //check top element
 public int top() {
  return stack.get(stack.size()-1);
 //check empty
 public boolean isEmpty() {
  if(stack.size()==0) return true;
  return false;
class Main{
 public static void main(String[] args) {
  //initialize stack
  Stack st = new Stack();
  System.out.println("Top element is: ";
  System.out.println("Top element is: ";
  System.out.println("Stack is empty? "+st.isEmpty());
  System.out.println("Stack is empty? "+st.isEmpty());

Top element is: 3
Top element is: 2
Stack is empty? false
Stack is empty? true

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala