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(){
  stack = new ArrayList<Integer>();
 }
 
 //add element
 public void push(int val) {
  stack.add(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();
  st.push(1);
  st.push(2);
  st.push(3);
  System.out.println("Top element is: "+st.top());
  st.pop();
  System.out.println("Top element is: "+st.top());
  System.out.println("Stack is empty? "+st.isEmpty());
  st.pop();
  st.pop();
  System.out.println("Stack is empty? "+st.isEmpty());
 }
}
Output:

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.

Comments

Popular Posts from this Blog

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

New Year Chaos Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala