What Is Stack in Data Structure Using C?

//

Scott Campbell

A stack is a fundamental data structure in computer science that follows the Last-In-First-Out (LIFO) principle. It is an abstract data type that serves as a collection of elements, where the addition and removal of items can only occur at one end known as the top. In this article, we will explore the concept of stacks in data structures using the C programming language.

Stack Operations

A stack has two primary operations:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes and returns the top element from the stack.

Additionally, we can also perform other operations on stacks:

  • Peek: Retrieves the top element without removing it from the stack.
  • isEmpty: Checks if the stack is empty or not.
  • isFull: Checks if the stack is full or not (in case of a fixed-size implementation).

Stack Implementation in C

In C, we can implement a stack using either an array or a linked list. Here, we will focus on implementing a stack using an array:

#include <stdio.h>
#define MAX_SIZE 100

// Stack variables
int stack[MAX_SIZE];
int top = -1;

// Push operation
void push(int item) {
    if (top >= MAX_SIZE - 1) {
        printf("Stack Overflow! Cannot push %d\n", item);
    } else {
        stack[++top] = item;
        printf("%d pushed to stack.\n", item);
    }
}

// Pop operation
int pop() {
    if (top < 0) {
        printf("Stack Underflow! Cannot pop from an empty stack.\n");
        return -1;
    } else {
        int item = stack[top--];
        return item;
    }
}

// Peek operation
int peek() {
    if (top < 0) {
        printf("Stack is empty.\n");
        return -1;
    } else {
        return stack[top];
    }
}

// Check if the stack is empty
int isEmpty() {
    return top == -1;
}

// Check if the stack is full
int isFull() {
    return top == MAX_SIZE - 1;
}

// Main function
int main() {
    push(10);
    push(20);
    push(30);

    printf("Top element: %d\n", peek());

    while (!isEmpty()) {
        printf("%d popped from stack.\n", pop());
    }

    printf("Is the stack empty? %s\n", isEmpty() ? "Yes" : "No");

    return 0;
}

Conclusion

A stack is a crucial data structure in computer science that provides efficient access and manipulation of elements. Understanding its operations and implementation in C will enable you to effectively utilize stacks in your programs.

Remember to consider the LIFO principle and be mindful of potential overflow or underflow errors. With this knowledge, you can confidently apply stacks to solve a wide range of programming problems.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy