Data Structure Slip No-2_A

 #include <stdio.h>

#include <string.h>

#include <conio.h>

#define MAX_SIZE 15

 // Stack data structure

struct Stack

{

    char data[MAX_SIZE];

    int top;

};

 // Function to initialize stack

void initialize(struct Stack *stack)

{

    stack->top = -1;

}

 // Function to check if the stack is empty

int isEmpty(struct Stack *stack)

{

    return (stack->top == -1);

}

 // Function to push an element onto the stack

void push(struct Stack *stack, char c)

{

    if (stack->top == MAX_SIZE - 1)

   {

        printf("Stack Overflow\n");

        return;

    }

    stack->data[++stack->top] = c;

}

// Function to pop an element from the stack

char pop(struct Stack *stack)

{

    if (isEmpty(stack))

   {

        printf("Stack Underflow\n");

        return '\0';

    }

    return stack->data[stack->top--];

}

 

void main()

{

    struct Stack stack;

    initialize(&stack);

    char input[MAX_SIZE];

    clrscr();

    printf("Enter a string: ");

    fgets(input, sizeof(input), stdin);

 

    // Remove the newline character

    input[strcspn(input, "\n")] = '\0'; 

    // Push each character onto the stack

    for (int i = 0; i < strlen(input); i++)

    {

        push(&stack, input[i]);

    }

 

    printf("Reversed string: ");

   

    // Pop and print characters from the stack

    while (!isEmpty(&stack))

    {

        printf("%c", pop(&stack));

    }

       printf("\n");

       getch();

}

 

Output:

Enter a string: ABCDE

Reversed string: EDCBA

 


No comments:

Post a Comment