Stacks & Queues
Dive into this core data structure concept.
**Stacks** and **Queues** are abstract data types, meaning they are defined by their behavior. In C, they are often implemented using either arrays or linked lists. A **Stack** follows the **LIFO (Last-In, First-Out)** principle. Think of a stack of plates. You can only add a new plate to the top, and you can only remove the topmost plate. The main operations are: - **push**: Add an element to the top. - **pop**: Remove the element from the top.
// A simple stack implementation using an array
#define STACK_SIZE 10
int stack[STACK_SIZE];
int top = -1; // Index of the top element
void push(int value) {
if (top < STACK_SIZE - 1) {
stack[++top] = value;
}
}
int pop() {
if (top >= 0) {
return stack[top--];
}
return -1; // Error or empty
}A **Queue** follows the **FIFO (First-In, First-Out)** principle. Think of a line at a ticket counter. The first person to get in line is the first person to be served. The main operations are: - **enqueue**: Add an element to the back of the queue. - **dequeue**: Remove the element from the front of the queue.
// A simple queue will be more complex to implement with a simple array.
// A circular array or a linked list is usually preferred.
// Here's the concept with a linked list implementation.
void enqueue(int value); // Adds to the 'tail' of the list
int dequeue(); // Removes from the 'head' of the listStacks are often used for managing function calls (the "call stack") and parsing expressions. Queues are used for managing tasks, like in operating system schedulers or printer queues.