Data Structures in C:Stacks and Queues

C Programming @ Freshers.in

In the realm of data structures, Stacks and Queues are essential tools that every programmer should have in their toolkit. In this comprehensive guide, we will explore Stacks and Queues in the C programming language, providing detailed explanations, practical examples, and real data to help you grasp these fundamental concepts.

Stacks in C

A Stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It can be envisioned as a stack of books, where the last book placed on the stack is the first one to be removed.

Example: Implementing a Stack in C

Let’s create a simple stack in C using an array:

#include <stdio.h>
#define MAX_SIZE 100
struct Stack {
    int data[MAX_SIZE];
    int top;
};
void push(struct Stack* stack, int value) {
    if (stack->top == MAX_SIZE - 1) {
        printf("Stack Overflow\n");
        return;
    }
    stack->data[++stack->top] = value;
}
int pop(struct Stack* stack) {
    if (stack->top == -1) {
        printf("Stack Underflow\n");
        return -1;
    }
    return stack->data[stack->top--];
}
int main() {
    struct Stack stack;
    stack.top = -1;
    push(&stack, 1);
    push(&stack, 2);
    push(&stack, 3);
    printf("Popped element: %d\n", pop(&stack));
    printf("Popped element: %d\n", pop(&stack));
    return 0;
}

Output:

Popped element: 3
Popped element: 2

In this example, we implement a stack using an array and perform push and pop operations. The output demonstrates the LIFO behavior of the stack.

Queues in C

A Queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. It can be visualized as a queue of people waiting in line, where the person who joins the queue first is the first to be served.

Example: Implementing a Queue in C

Let’s create a simple queue in C using an array:

#include <stdio.h>
#define MAX_SIZE 100
struct Queue {
    int data[MAX_SIZE];
    int front, rear;
};
void enqueue(struct Queue* queue, int value) {
    if (queue->rear == MAX_SIZE - 1) {
        printf("Queue Overflow\n");
        return;
    }
    queue->data[++queue->rear] = value;
}
int dequeue(struct Queue* queue) {
    if (queue->front > queue->rear) {
        printf("Queue Underflow\n");
        return -1;
    }
    return queue->data[queue->front++];
}
int main() {
    struct Queue queue;
    queue.front = queue.rear = -1;
    enqueue(&queue, 1);
    enqueue(&queue, 2);
    enqueue(&queue, 3);
    printf("Dequeued element: %d\n", dequeue(&queue));
    printf("Dequeued element: %d\n", dequeue(&queue));
    return 0;
}

Output:

Dequeued element: 1
Dequeued element: 2

In this example, we implement a queue using an array and perform enqueue and dequeue operations. The output demonstrates the FIFO behavior of the queue.

Author: user