Stacks and Queues
In the world of software development, stacks and queues are fundamental data structures that are widely used in solving a variety of problems. These data structures provide efficient ways to store and manipulate data, and they have numerous applications across different domains.
Stacks
A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. It functions like a real-life stack of plates, where the last plate placed on top is the first one to be removed. Stacks are commonly used in scenarios such as function calls, expression evaluation, and backtracking.
Let's take a look at an example of implementing a stack in Java:
1import java.util.Stack;
2
3public class StackExample {
4 public static void main(String[] args) {
5 Stack<Integer> stack = new Stack<>();
6
7 // Pushing elements onto the stack
8 stack.push(1);
9 stack.push(2);
10 stack.push(3);
11
12 // Popping elements from the stack
13 while (!stack.isEmpty()) {
14 System.out.println(stack.pop());
15 }
16 }
17}
The output of the above code will be:
13
22
31
Queues
A queue is a data structure that follows the First-In-First-Out (FIFO) principle. It functions like a queue of people waiting for their turn, where the person who arrives first is the first one to be served. Queues are commonly used in scenarios such as task scheduling, resource allocation, and message processing.
Here's an example of implementing a queue in Java:
1import java.util.LinkedList;
2import java.util.Queue;
3
4public class QueueExample {
5 public static void main(String[] args) {
6 Queue<Integer> queue = new LinkedList<>();
7
8 // Enqueuing elements into the queue
9 queue.add(1);
10 queue.add(2);
11 queue.add(3);
12
13 // Dequeuing elements from the queue
14 while (!queue.isEmpty()) {
15 System.out.println(queue.poll());
16 }
17 }
18}
The output of the above code will be:
11
22
33
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// Hello World
System.out.println("Hello, World!");
}
}