10.1 C
Delhi
Thursday, December 26, 2024

IMPLEMENTATION OF STACK IN C

Must read

Stack is a linear data structure where we can arrange our elements in a LIFO style (i.e, Last In First Out ). It is a versatile concept which is used everywhere in our day to day life like stack of bread, stack of books etc.

There are different operations of stack in data structure which includes push ( ) operation used to insert an element in the stack, pop ( ) operation used to remove an element from the stack and returns it, IsFull ( ) operation performed in stack used to check whether the stack is full or not, isEmpty ( ) operation checks whether the stack is empty or not.

We can easily implement stack using array or linked list both but specifically we are looking at how the implementation of stack in c is performed using array first then we move forward with the linked list implementation.

implementation of stack in c programming

Implementation of Stack in C using Arrays

The program demonstrates the implementation of a stack in C using a fixed-size array.

It is implemented using a stack structure containing an array to store elements (arr_stack) and an integer (top_pointer) to track the index of the top element.

Key operations include initStack to initialize the stack, push_operation to add an element to the stack if it’s not full, pop_operation to remove and return the topmost element if the stack isn’t empty, and peek_operation view the top element without removal.

The display_elements function shows all stack elements, while the program handles errors such as stack overflow and underflow during operations.

A menu-driven interface allows users to interact with the stack, performing operations like push, pop, peek, display, and exit. This implementation is an efficient way to understand and demonstrate stack operations in C.

#include <stdio.h>
#define MAX_SIZE 100

// Stack structure
typedef struct {
    int arr_stack[MAX_SIZE];
    int top_pointer;
} Stack;

// Function prototypes
void initStack(Stack *p);
int isFull_operation(Stack *p);
int isEmpty_operation(Stack *p);
void push_operation(Stack *p, int value);
int pop_operation(Stack *p);
int peek_operation(Stack *p);
void display_elements(Stack *p);

int main() {
    Stack stack_datastructure;
    int choice, value;

    initStack(&stack_datastructure);

    do {
        printf("\nStack Operations:\n");
        printf("1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
        case 1:
            printf("Enter value to push: ");
            scanf("%d", &value);
            push_operation(&stack_datastructure, value);
            break;
        case 2:
            value = pop_operation(&stack_datastructure);
            if (value != -1)
                printf("Popped value: %d\n", value);
            break;
        case 3:
            value = peek_operation(&stack_datastructure);
            if (value != -1)
                printf("Top value: %d\n", value);
            break;
        case 4:
            display_elements(&stack_datastructure);
            break;
        case 5:
            printf("Exiting...\n");
            break;
        default:
            printf("Invalid choice! Please try again.\n");
        }
    } while (choice != 5);

    return 0;
}

// Initialize the stack
void initStack(Stack *p) {
    p->top_pointer = -1;
}

// Check if the stack is full
int isFull_operation(Stack *p) {
    return p->top_pointer == MAX_SIZE - 1;
}

// Check if the stack is empty
int isEmpty_operation(Stack *p) {
    return p->top_pointer == -1;
}

// Push an element onto the stack
void push_operation(Stack *p, int value) {
    if (isFull_operation(p)) {
        printf("Stack overflow! Cannot push %d.\n", value);
    } else {
        p->arr_stack[++p->top_pointer] = value;
        printf("%d pushed onto the stack.\n", value);
    }
}

// Pop an element from the stack
int pop_operation(Stack *p) {
    if (isEmpty_operation(p)) {
        printf("Stack underflow! No elements to pop.\n");
        return -1;
    } else {
        return p->arr_stack[p->top_pointer--];
    }
}

// Peek the top element of the stack
int peek_operation(Stack *p) {
    if (isEmpty_operation(p)) {
        printf("Stack is empty! No top element.\n");
        return -1;
    } else {
        return p->arr_stack[p->top_pointer];
    }
}

// Display all elements in the stack
void display_elements(Stack *p) {
    if (isEmpty_operation(p)) {
        printf("Stack is empty! Nothing to display.\n");
    } else {
        printf("Stack elements: ");
        for (int i = 0; i <= p->top_pointer; i++) {
            printf("%d ", p->arr_stack[i]);
        }
        printf("\n");
    }
}

OUTPUT

Implementation of Stack in C using Linked list

The program demonstrates the implementation of a stack in C using a linked list, which allows dynamic memory allocation, enabling the stack to grow or shrink as needed. Each stack node contains a value (element) and a pointer to the next node (next_pointer).

Key operations include push_operation, which adds a new node to the top of the stack, and pop_operation, which removes and returns the top element while freeing its memory.

The peek_operation function retrieves the top element without removing it, and isEmpty_operation checks if the stack is empty. The display_elements function traverses the stack to print all elements from top to bottom.

The program handles stack underflow for empty stacks during pop and peek operations and ensures error handling for memory allocation failures.

The main function demonstrates these operations by pushing elements onto the stack, displaying them, peeking at the top, popping an element, and verifying if the stack is empty.

This implementation efficiently handles dynamic stacks, offering flexibility over fixed-size array-based stacks.

#include <stdio.h>
#include <stdlib.h>

// Define the structure of a stack node
typedef struct Node {
    int element;
    struct Node* next_pointer;
} Linked_Node;

// Function to create a new node
Linked_Node* creatingNode(int element) {
    Linked_Node* newNode1 = (Linked_Node*)malloc(sizeof(Linked_Node));
    if (!newNode1) {
        printf("Memory allocation failed\n");
        exit(1);
    }
    newNode1->element = element;
    newNode1->next_pointer = NULL;
    return newNode1;
}

// Push operation: Add an element to the top of the stack
void push_operation(Linked_Node** top_pointer, int element) {
    Linked_Node* newNode1 = creatingNode(element);
    newNode1->next_pointer = *top_pointer;
    *top_pointer = newNode1;
    printf("Element = %d inserted onto the stack\n", element);
}

// Pop operation: Remove and return the top element of the stack
int pop_operation(Linked_Node** top_pointer) {
    if (*top_pointer == NULL) {
        printf("Stack underflow! No elements to pop.\n");
        return -1;
    }
    Linked_Node* temp = *top_pointer;
    int popped_element = temp->element;
    *top_pointer = (*top_pointer)->next_pointer;
    free(temp);
    return popped_element;
}

// Peek operation: Return the top element without removing it
int peek_operation(Linked_Node* top_pointer) {
    if (top_pointer == NULL) {
        printf("Stack is empty. No top element.\n");
        return -1;
    }
    return top_pointer->element;
}

// Check if the stack is empty
int isEmpty_operation(Linked_Node* top_pointer) {
    return top_pointer == NULL;
}

// Display the stack
void display_elements(Linked_Node* top_pointer) {
    if (top_pointer == NULL) {
        printf("Stack is empty.\n");
        return;
    }
    printf("Stack elements:\n");
    Linked_Node* temp = top_pointer;
    while (temp != NULL) {
        printf("%d -> ", temp->element);
        temp = temp->next_pointer;
    }
    printf("NULL\n");
}

// Main function to demonstrate stack operations
int main() {
    Linked_Node* stack_datastructure = NULL;

    // Stack operations
    push_operation(&stack_datastructure, 45);
    push_operation(&stack_datastructure, 98);
    push_operation(&stack_datastructure, 36);

    display_elements(stack_datastructure);

    printf("Element on the top of the stack: %d\n", peek_operation(stack_datastructure));

    printf("Displaying popped element from the stack: %d\n", pop_operation(&stack_datastructure));

    display_elements(stack_datastructure);

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

    return 0;
}

OUTPUT

implementation of stack in c using Linked list

Conclusion

In this blog we have covered the implementation of stack in c programming language using array and linked list data structure. We have covered basic operations in stack like push ( ) operation , pop ( ) operation, peek ( ) operation, isEmpty ( ) and isFull ( ) operation.

Practical implementation of stack in c using array and linked list extends your understanding of how basic operations actually performed on stack.

Join India's Largest CAT Communityspot_img
Course on Demandspot_img

Latest article