Stacks and Queues in Java
Stacks and Queues in Java
Welcome to an exciting exploration of two fundamental data structures in Java: Stacks and Queues! These data structures organize and manage data effectively. Specifically, stacks are comparable to a pile of plates, while queues are akin to standing in line. Let's dive in!
Stacks: Last In, First Out (LIFO)
A stack follows the "Last In, First Out" or LIFO principle. Imagine a stack of plates where the last plate added is the first one to be removed. In Java, we can use ArrayDeque<E> or LinkedList<E> to implement a stack, with push for inserting (pushing) and pop for removing (popping, returning the element that is removed).
- Push (Insertion): Adds an element to the top of the stack. This makes the newly added element the last-in, which is the first to be removed when needed.
- Pop (Removal): Removes and returns the element at the top of the stack, following the Last In, First Out (LIFO) principle.
Let's explore this with an example of a stack of plates.
The last plate added was removed first, demonstrating the LIFO property of a stack.
Queues: First In, First Out (FIFO)
A queue operates on the "First In, First Out" or FIFO principle, similar to waiting in line. In Java, we can implement a queue using the Queue<E> interface with a LinkedList or ArrayDeque, where add (enqueue) inserts at the end and remove or poll (dequeue) removes from the front.
- Add (Enqueue): Adds an element to the end of the queue, following the First In, First Out (FIFO) order.
- Poll (Dequeue): Removes and returns the element at the front of the queue. This is the oldest element, maintaining the FIFO order.
Let's examine this with a queue of people.
Here, Person 1, the first to join the queue, left before Person 2, demonstrating the FIFO property of a queue.
