How to remove a specific element from Queue

29 Sep, 2021
Given a queue q[] and an integer K, the task is to define a method to remove a specific element from the queue q[]. If there are multiple occurrences of element K, then, remove the first one from the queue q[].
Examples:
Input: q[] = {10, 20, 30, 40, 50, 60}, K = 30Output: {10, 20, 40, 50, 60}Explanation: After removal of 30, the queue becomes {10, 20, 40, 50, 60}.
Input: q[] = {1, 2, 3, 3}, K = 3Output: {1, 2, 3}Explanation: After removal of the first occurrence of 3, the queue becomes {1, 2,  3}. 
Approach: The idea is to create a temporary queue ref[] and store all the elements in it, until K is found. Then, remove K from the original queue q[], and insert the remaining elements back into the queue q[]. Follow the steps below to solve the problem:
Initialize a helper queue ref to store the elements of the queue q[] temporarily.
Initialize variables s as the size of the queue q[] and cnt as 0 to store the count of numbers pushed into the helper queue ref[].
Iterate in a while loop till the queue q[] is not empty and the front of the queue is not equal to the desired element K:Enqueue the front element of the queue q[] into the queue ref[].Dequeue an element from the queue q[].Increase the value of cnt by 1.
Enqueue the front element of the queue q[] into the queue ref[].
Dequeue an element from the queue q[].
Increase the value of cnt by 1.
If the queue q[] is empty, then the element K is not present in the queue q[], so print “element not found!!” and perform the following steps:Iterate in a while loop till the queue ref[] is not empty:Enqueue the front element of the queue ref[] into the queue q[].Dequeue an element from the queue ref[].
Iterate in a while loop till the queue ref[] is not empty:Enqueue the front element of the queue ref[] into the queue q[].Dequeue an element from the queue ref[].
Enqueue the front element of the queue ref[] into the queue q[].
Dequeue an element from the queue ref[].
Else, the element is found, so Dequeue an element from the queue q[] and performs the following steps:Iterate in a while loop till the queue ref[] is not empty:Enqueue the front element of the queue ref[] into the queue q[].Dequeue an element from the queue ref[].
Iterate in a while loop till the queue ref[] is not empty:Enqueue the front element of the queue ref[] into the queue q[].Dequeue an element from the queue ref[].
Enqueue the front element of the queue ref[] into the queue q[].
Dequeue an element from the queue ref[].
Initialize the variable k as s-cnt-1 to mark the number of elements required to dequeue from the queue q[] and enqueue back again to the queue q[].
Iterate in a while loop till K is greater than 0 and perform the following steps:Subtract the value of K by 1.Enqueue the front element of the queue q[] into the queue q[].Dequeue an element from the queue q[].
Subtract the value of K by 1.
Enqueue the front element of the queue q[] into the queue q[].
Dequeue an element from the queue q[].
After performing the above steps, print the elements of the queue q[].
Below is the implementation of the above approach.
C++
Java
C#
// C++ program for the above approach.#include <bits/stdc++.h>using namespace std; // Function to remove an element from// the queuevoid remove(int t, queue<int>& q){     // Helper queue to store the elements    // temporarily.    queue<int> ref;    int s = q.size();    int cnt = 0;     // Finding the value to be removed    while (q.front() != t and !q.empty()) {        ref.push(q.front());        q.pop();        cnt++;    }     // If element is not found    if (q.empty()) {        cout << "element not found!!" << endl;        while (!ref.empty()) {             // Pushing all the elements back into q            q.push(ref.front());            ref.pop();        }    }     // If element is found    else {        q.pop();        while (!ref.empty()) {             // Pushing all the elements back into q            q.push(ref.front());            ref.pop();        }        int k = s - cnt - 1;        while (k--) {             // Pushing elements from front of q to its back            int p = q.front();            q.pop();            q.push(p);        }    }} // Function to print all the elements// of the queue.void print(queue<int> qr){    while (!qr.empty()) {        cout << qr.front() << " ";        qr.pop();    }    cout << endl;} // Driver Codeint main(){    queue<int> q;     // Pushing into the queue    q.push(10);    q.push(20);    q.push(30);    q.push(40);    q.push(50);    q.push(60);    print(q);     // Removing 39 from the queue    remove(39, q);    print(q);     // Removing 30 from the queue    remove(30, q);    print(q);    return 0;}
// Java program for the above approach. import java.util.*; class GFG{ // Function to remove an element from// the queuestatic Queue<Integer> q;static void remove(int t){     // Helper queue to store the elements    // temporarily.    Queue<Integer> ref = new LinkedList<>();    int s = q.size();    int cnt = 0;     // Finding the value to be removed    while (!q.isEmpty() && q.peek() != t) {        ref.add(q.peek());        q.remove();        cnt++;    }     // If element is not found    if (q.isEmpty()) {        System.out.print("element not found!!" +"\n");        while (!ref.isEmpty()) {             // Pushing all the elements back into q            q.add(ref.peek());            ref.remove();        }    }     // If element is found    else {        q.remove();        while (!ref.isEmpty()) {             // Pushing all the elements back into q            q.add(ref.peek());            ref.remove();        }        int k = s - cnt - 1;        while (k-- >0) {             // Pushing elements from front of q to its back            int p = q.peek();            q.remove();            q.add(p);        }    }} // Function to print all the elements// of the queue.static void print(){    Queue<Integer> qr = new LinkedList<>(q);    while (!qr.isEmpty()) {        System.out.print(qr.peek()+ " ");        qr.remove();    }     System.out.println();} // Driver Codepublic static void main(String[] args){    q = new LinkedList<>();     // Pushing into the queue    q.add(10);    q.add(20);    q.add(30);    q.add(40);    q.add(50);    q.add(60);    print();     // Removing 39 from the queue    remove(39);    print();     // Removing 30 from the queue    remove(30);    print();}} // This code is contributed by 29AjayKumar
// C# program for the above approach.using System;using System.Collections;public class GFG{           // Function to remove an element from// the queuestatic Queue q = new Queue();static void remove_(int t){     // Helper queue to store the elements    // temporarily.    Queue reff = new Queue();    int s = q.Count;    int cnt = 0;     // Finding the value to be removed    while ((int)q.Count != 0 && (int)q.Peek() != t) {               reff.Enqueue(q.Peek());        q.Dequeue();        cnt++;    }     // If element is not found    if (q.Count == 0) {        Console.WriteLine("element not found!!");                   while (reff.Count != 0) {                         // Pushing all the elements back into q            q.Enqueue(reff.Peek());            reff.Dequeue();        }    }     // If element is found    else {        q.Dequeue();        while (reff.Count != 0) {             // Pushing all the elements back into q            q.Enqueue(reff.Peek());            reff.Dequeue();        }        int k = s - cnt - 1;        while (k-- >0) {             // Pushing elements from front of q to its back            int p = (int)q.Peek();            q.Dequeue();            q.Enqueue(p);        }    }} // Function to print all the elements// of the queue.static void print(){    Queue qr = (Queue)q.Clone();    while (qr.Count != 0) {        Console.Write(qr.Peek()+ " ");        qr.Dequeue();    }     Console.WriteLine();} // Driver Codestatic public void Main (){     // Pushing into the queue    q.Enqueue(10);    q.Enqueue(20);    q.Enqueue(30);    q.Enqueue(40);    q.Enqueue(50);    q.Enqueue(60);       print();     // Removing 39 from the queue    remove_(39);    print();     // Removing 30 from the queue    remove_(30);    print();}} // This code is contributed by Dharanendra L V.
10 20 30 40 50 60 
element not found!!
10 20 30 40 50 60 
10 20 40 50 60 
Time Complexity: O(N)Auxiliary Space: O(N)
29AjayKumar
dharanendralv23
STL
Queue
Queue
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Sum of minimum and maximum elements of all subarrays of size k.
Reversing a Queue
First negative integer in every window of size k
Implement Stack and Queue using Deque
Priority queue of pairs in C++ with ordering by first and second element
Stack Permutations (Check if an array is stack permutation of other)
Interleave the first half of the queue with second half
Find the first non-repeating character from a stream of characters