C Stacks and Queues
A stack is a Last-In-First-Out (LIFO) data structure: the last element added is the first removed, like a stack of plates. A queue is First-In-First-Out (FIFO): the first element added is the first removed, like a line of people.
Both can be implemented in C using arrays or linked lists, and are fundamental building blocks used in algorithms like parsing, scheduling, and breadth-first search.
push(stack, value); pop(stack);
enqueue(queue, value); dequeue(queue);Stack operations
A stack supports push (add to the top) and pop (remove from the top). Using a simple array with a 'top' index is a common, efficient implementation.
Queue operations
A queue supports enqueue (add to the back) and dequeue (remove from the front). Arrays or linked lists with separate front and back indexes/pointers implement queues efficiently.
#include <stdio.h>
int main() {
int stack[3];
int top = -1;
stack[++top] = 10;
stack[++top] = 20;
printf("%d\n", stack[top--]);
return 0;
}2020 was pushed last, so it is popped first, demonstrating LIFO order.
#include <stdio.h>
int main() {
int queue[3] = {10, 20, 30};
int front = 0;
printf("%d\n", queue[front++]);
return 0;
}1010 was added first, so it is removed first, demonstrating FIFO order.
Key points
- A stack is Last-In-First-Out (LIFO): push and pop happen at the top.
- A queue is First-In-First-Out (FIFO): enqueue at the back, dequeue from the front.
- Both can be implemented using arrays or linked lists.
- Stacks are used in function call management; queues are used in task scheduling.
