
Introduction
A queue data structure is one of the crucial topics of interviews asked by an interviewer in technical rounds. Due to its principle of first come, first served, it is used where things don't have to be processed easily. There are primarily four basic operations performed on queue:
- Front, Rear, Enqueue, Dequeue
Out of several different queue methods, we will be exploring the remove() method in the Java language. The remove() method removes and returns the element at the front of the pile; it deletes the head of the pile. This method is different from the poll() method as the remove() method throws an exception if the queue is empty.
Also see, Linked Lists
Syntax:-
Parameters: e remove()
Returns: the head of the queue
Throws: NoSuchElementException(When queue is empty)
Example:
Input: 1 2 3 4
Output: 1(returned element)
2 3 4 (queue after removing the head)
Approach 1: Using ArrayDeque
ArrayDeque provides a resizable array in addition to the implementation of the deque. It implements both queue and deque.
Code
import java.util.*;
public class Solution {
public static void main(String[] args)
throws IllegalStateException{
// using arraydeque
Queue<Integer> Q = new ArrayDeque<Integer>();
// Add numbers to end of Queue
Q.add(7);
Q.add(3);
Q.add(5);
Q.add(6);
// print queue
System.out.println("Queue: " + Q);
// use remove() method
System.out.println("Queue's head: " + Q.remove());
// after using the remove() method
System.out.println("Queue: " + Q);
// use remove() method
System.out.println("Queue's head: " + Q.remove());
}
}
Output
Queue: [7, 3, 5, 6] Queue's head: 7 Queue: [3, 5, 6] Queue's head: 3 |