Queue is an ordered list in which insertions are done at one end (back) and deletions are done at other end (front). The first element to be inserted is the first one to be deleted. Hence, it is called First in First out (FIFO) or Last in Last out (LILO) list.
In general, a queue is a line of people or things waiting to be served in sequential order starting at the beginning of the line or sequence.
When an element is inserted in a queue, the concept is called EnQueue, and when an element is removed from the queue, the concept is called DeQueue. DeQueueing an empty queue is called underflow and EnQueuing an element in a full queue is called overflow.
peek()
function is oftenly used to return the value of first element without dequeuing it.Queue, as the name suggests is used whenever we need to manage any group of objects in an order in which the first one coming in, also gets out first while the others wait for their turn, like in the following scenarios:
Just like Stack, in case of a Queue too, we know exactly, on which position new element will be added and from where an element will be removed, hence both these operations requires a single step.
Queue can be implemented using an Array, List, or Linked List. LinkedList has the best performance.
@Data @NoArgsConstructor public class MyQueue<E> { private LinkedList<E> list = new LinkedList<>(); public E enqueue(E item) { list.addFirst(item); return item; } public E dequeue() { if (list.size() <= 0) { throw new EmptyStackException(); } return list.removeLast(); } public int getSize() { return list.size(); } public void print() { int size = getSize(); int count = 1; if (count >= size) { return; } E item = list.getFirst(); while (item != null) { System.out.println(item.toString()); if (count >= size) { break; } item = list.get(count); count++; } } }