Sunday 29 September 2024

Write a Program to reverse a string using stack


Method1

#include <stdio.h>

#include <string.h>


#define max 100 // Define maximum size of the stack


int top = -1, stack[max]; // Initialize top and the stack


void push(char x) {

    // Push (Inserting Element in stack) operation

    if (top == max - 1) {

        printf("Stack overflow\n");

    } else {

        stack[++top] = x; // Push the character onto the stack

    }

}


void pop() {

    // Pop (Removing element from stack)

    if (top == -1) { // Check if stack is empty

        printf("Stack underflow\n");

    } else {

        printf("%c", stack[top--]); // Print and remove the top character

    }

}


int main() {

    char str[max]; // Array to store the string


    // Input the string

    printf("Enter string: ");

    scanf("%s", str); // Read string input


    int len = strlen(str); // Get the length of the string

    int i;


    // Push each character of the string onto the stack

    for (i = 0; i < len; i++) {

        push(str[i]);

    }


    // Pop characters from the stack to reverse the string

    printf("Reversed string: ");

    for (i = 0; i < len; i++) {

        pop(); // Call pop to print each character in reverse

    }

    printf("\n");


    return 0; 

}