Queue Data Structure - The Coding Shala

Home >> Data Structures >> Queue

Queue Data Structure

In this post, we will see the basics of the queue. The queue is a Data Structure, also known as the First-in-first-out data structure(FIFO). In a queue, there are two main operations: Enqueue and Dequeue. The insert Operation is called enqueue and the new element is always added at the end of the queue. The delete operation is called dequeue and we only allowed to remove the first element.

Queue Java Program

The following is a simple implementation of the queue: 

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

//Queue implementation

class MyQueue{
 //to store data
 private List<Integer> data;
 private int q_start; //start point of queue
 
 //initial state
 MyQueue(){
  data = new ArrayList<Integer>();
  q_start = 0;
 }
 
 //Enqueue Operation
 //add element at the end of queue are return true if successful
 public boolean EnQueue(int element) {
  data.add(element);
  return true;
 }
 
 //DeQueue operation
 //remove element if there any
 //move start pointer
 public boolean DeQueue() {
  if(isEmpty()) return false;
  q_start++;
  return true;
 }
 
 //check is empty or not
 public boolean isEmpty() {
  if(data.size() <= q_start) return true;
  return false;
 }
 
 //return first element
 public int Front(){
  if(isEmpty()) return -1;
  return data.get(q_start);
 }
 
}


public class Main{
 public static void main(String[] args) {
  MyQueue queue = new MyQueue();
  queue.EnQueue(4);
  queue.EnQueue(5);
  queue.EnQueue(6);
  if(queue.isEmpty() == false) { //check if not empty
   System.out.println("First Element is: "+queue.Front());
  }
  queue.DeQueue();
  if(queue.isEmpty() == false) { //check if not empty
   System.out.println("First Element is: "+queue.Front());
  }
  queue.DeQueue();
  System.out.println("First Element is: "+queue.Front());
  
  queue.DeQueue();
  //now queue is empty  will return -1
  System.out.println("First Element is: "+queue.Front());
  
  if(queue.isEmpty() == false) { //check if not empty
   System.out.println("First Element is: "+queue.Front());
  }else {
   System.out.println("Queue is Empty");
  }
 }
}
Output: 

First Element is: 4
First Element is: 5
First Element is: 6
First Element is: -1
Queue is Empty


Other Posts You May Like
Please leave a comment below if you like this post or found some error, 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

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala