Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a java program that implements a Queue. Operations to implement: Enqueue/p

ID: 3575419 • Letter: W

Question

Write a java program that implements a Queue. Operations to implement:

Enqueue/push (E): Add an element to the end of the sequence

Dequeue/pop: Remove an element from the start of the sequence

Front/Peek: Return the first element of the sequence without removing it (what the head is pointing to)

atIndex(x): Return the element at the given index (x) Or throw an exception if it is out of bound (if you can control the user input then do that instead)

Size: Return the size of the Queue

isEmpty: Boolean, returns true if the Queue is empty

Empty: Empty the Queue

Back: Return what the tail is pointing to

Explanation / Answer

HI, Please find my implementation.

Please let me know in case of any issue.

################ Queue.java #############

import java.util.ArrayList;

public class Queue<E> {

  

   // list that stores queue elements

   private ArrayList<E> queue;

  

   public Queue() {

       queue = new ArrayList<E>();

   }

  

   public void Enqueue(E item){

       queue.add(item); // adding at last

   }

  

   public E Dequeue(){

       if(queue.size() == 0)

           return null;

      

       return queue.remove(0);

   }

  

   public E Front(){

       if(queue.size() == 0)

           return null;

      

       return queue.get(0);

   }

  

   public E atIndex(int x){

       if(x < 0 || x >=queue.size()){

           throw new ArrayIndexOutOfBoundsException("index is out of bound");

       }

      

       return queue.get(x);

   }

  

   public int Size(){

       return queue.size();

   }

   public boolean isEmpty(){

       return queue.size() == 0;

   }

  

   public void Empty(){

       queue = new ArrayList<E>();

   }

  

   public E Back(){

       if(isEmpty())

           return null;

       return queue.get(Size()-1);

   }

}

################### QueueTest.java ################

public class QueueTest {

   public static void main(String[] args) {

      

       // creating queue Object

       Queue<Integer> queue = new Queue<Integer>();

      

       queue.Enqueue(34);

       queue.Enqueue(14);

       queue.Enqueue(55);

       queue.Enqueue(87);

      

       System.out.println("Size: "+queue.Size());

       System.out.println("Front: "+queue.Front());

      

       System.out.println("Deueue: "+queue.Dequeue());

      

       System.out.println("Front: "+queue.Front());

      

       System.out.println("Size: "+queue.Size());

   }

}

/*

Sample run:

Size: 4

Front: 34

Deueue: 34

Front: 14

Size: 3

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote