Question: Queue, unlike a stack, has the first in, first out principle that is data added first will be removed first. In most languages, this data
Queue, unlike a stack, has the “first in, first out” principle that is data added first will be removed first. In
most languages, this data structure is already implemented in some language library already.
In C++, the STL (Stand Template Library) queue provides the functionality of a queue data structure. One
example to use it as follows:
#include
#include
using namespace std;
int main() {
// create a queue of string
queue students;
// push elements into the queue
students.push("Alice");
students.push("Bob");
cout << "Queue: ";
// print elements of queue
// loop until queue is empty
while(!students.empty()) {
// print the element
cout << students.front() << ", ";
// pop element from the queue
students.pop();
}
cout << endl;
return 0;
}
Java has Queue interface and its methods which extends Collection interface. And there are classes that
implement it: ArrayDeque, LinkedList, PriorityQueue. One example to use LinkedList:
1
import java.util.Queue;
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
// Creating Queue using the LinkedList class
Queue students = new LinkedList<>();
// offer elements to the Queue
students.offer("Alice");
students.offer("Bob");
System.out.println("Queue: " + students );
// Access elements of the Queue
String accessedStudent = students.peek();
System.out.println("Accessed Element: " + accessedStudent);
// Remove elements from the Queue
String removedStudent = students.poll();
System.out.println("Removed Element: " + removedStudent);
System.out.println("Updated Queue: " + students);
}
}
Step by Step Solution
There are 3 Steps involved in it
In C youre using the STLs queue class You push elements i... View full answer
Get step-by-step solutions from verified subject matter experts
