In: Computer Science
write a method in java that insert First(Queue<E> s E e)that receives a queue and an elment, it inserts the element at the beginnings of queue
Idea
A queue data structure works on the first-in-first-out (FIFO) logic. It mainly supports 2 methods
Now, since we don't have any method to push or insert an element to the front of the queue, we can use the following idea: Create an empty queue. Add the new element to it's back. Then, push all the elements from the original queue to this new queue by popping them one at a time and push to the new queue. Now, we again pop all the elements from this new queue and push back to the original queue. This way, the new element is now at the front of the original queue.
The code and output are attached below. Helpful comments are also added to the code.
Note: Queue interface is implemented as a LinkedList (or PriorityQueue) in Java. But, the concept remains the same.
Code
import java.util.LinkedList;
public class QueueClass {
public static void insert(LinkedList<Integer> q, Integer e) {
// Create an empty queue
LinkedList<Integer> new_q = new LinkedList<>();
// Push new element to queue end
new_q.add(e);
// Pop all elements from front of original queue and push to end of new queue
while (q.size() > 0)
new_q.add(q.removeFirst());
// Now, pop all elements from front of new queue and push to end original queue
while (new_q.size() > 0)
q.add(new_q.removeFirst());
// Now, the original queue contains the new element at its front.
}
public static void main(String[] args) {
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(1);
queue.add(2);
queue.add(3);
System.out.println("Elements of queue before insertion " + queue);
insert(queue, 4);
System.out.println("Elements of queue after insertion " + queue);
}
}
Output