A Queue is also a data structure used to temporarily store elements. Unlike a Stack, it has the FIFO (First-In-First-Out) property, meaning the element that enters the queue first comes out first, and new elements are added to the tail of the queue.
Queues are usually used in systems that need ordering consistency, like network packet processing, OS process scheduling, BFS, and so on. Think of it like waiting in line to buy tickets.
Queue operations:
Front of the line: front
Back of the line: back
Enter the line: push, can only enter from the back
Leave the line: pop, can only leave from the front
Push(data): put data into the queue from the back and update it to the new back; adding data to the queue is also called enqueue
Pop: remove the data pointed to by front from the queue and update front; removing data from the queue is also called dequeue
getFront: return the data pointed to by front
getBack: return the data pointed to by back
IsEmpty: check whether the queue has any data
getSize: return the number of data items in the queue
Queue implementation (C++)
Implementing a Queue with a Linked List
The queue’s front is the first node of the linked list, and back is the last node of the list
But since a queue needs getFront and getBack, besides a pointer tracking the front node we also need a pointer tracking the back node
empty queue After push 24: //1 front: 24 back: 24 After push 8: //2 front: 24 back: 8 After push 23: //3 front: 24 back: 23 After push 13: //4 front: 24 back: 13 After pop the front element: //5 After push 35: front: 8 back: 35 //6 After pop the front element: front: 23 back: 35 //7 After pop the front element: front: 13 back: 35 //8 After pop the front element: front: 35 back: 35 //9 After pop the front element: Queue is empty. //10
After Pushing 25: front:25 back:25 After Pushing 50: front:25 back:50 After Pushing 77: front:25 back:77 After Poping the front element: front:50 back:77 After Poping the front element: front:77 back:77 empty queue empty queue After Poping the front element: front:-1 back:-1
Queue-related STL
C++ also has a ready-made STL for queue. Before using it you need to declare <queue>. Below are the common member functions: