C ยท Chapter 42 of 45

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.

Syntax
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.

Example 1 (c)
#include <stdio.h>

int main() {
  int stack[3];
  int top = -1;
  stack[++top] = 10;
  stack[++top] = 20;
  printf("%d\n", stack[top--]);
  return 0;
}
Output
20

20 was pushed last, so it is popped first, demonstrating LIFO order.

Example 2 (c)
#include <stdio.h>

int main() {
  int queue[3] = {10, 20, 30};
  int front = 0;
  printf("%d\n", queue[front++]);
  return 0;
}
Output
10

10 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.
๐Ÿ’ก Note: The function call stack itself is a real-world example of the stack data structure in action.

๐Ÿ“ Quick Quiz

1. What order does a stack follow?

2. What order does a queue follow?

3. Which operation removes an element from a stack?