Similarly to a Stack, a Queue is a linear data structure where the elements are inserted and removed in a specific order. It follows the FIFO (First In, Last Out) principle, where the first added element is the first one to be removed.
A Queue can be represented as an array or a linked list. In the case of an array, we need to store the indexes of the first and last stored elements. For the linked list, we need to have pointers to the head and tail list nodes.
βοΈ
Queue implementation using an array causes memory wastage because the space of the dequeued element can stay unused.
publicclassQueueLinkedList<T>{privateclassNode{publicTvalue;publicNodenext;}privateNodehead;// "end" of the queueprivateNodetail;// "start" of the queue// Add an element to the start of the queuepublicvoidenqueue(Tvalue){Nodenode=newNode();node.value=value;if(isEmpty()){head=node;}else{tail.next=node;}tail=node;}// Take and remove the element at the end of the queuepublicTdequeue(){Tvalue=head.value;if(tail==head)tail=head.next;head=head.next;returnvalue;}publicTpeek(){returnhead.value;}}
π
The complete QueueArray and QueueLinkedList implementations are available here.