Write c program for reverse the given string using stack

Reverse string using stack

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define max 50

//To create structure stack
struct STACK
{
char item[max];
   int top;
};
typedef struct STACK stack;

//To define functions
void push(stack *, char);
char pop(stack *);
void reverse(char []);
int isempty(int);
int isfull(int);

void main()
{
char ch[50];
   printf("\nEnter the string: ");
   gets(ch);
   printf("\nEntered string is: %s",ch);
   printf("\nReverse of string is: ");
   reverse(ch);
   getch();
}

//To add elements in stack
void push(stack *s, char data)
{
if(isfull(s->top))
   printf("\nStack full.");
   else
   {
    s->top++;
      s->item[s->top]=data;
   }
}

//To check stack is full or not
int isfull(int top)
{
if(top==max)
   return 1;
   else
   return 0;
}

//To remove elements from stack
char pop(stack *s)
{
char data;
if(isempty(s->top))
   {
   printf("\nStack is EMPTY");
   }
   else
   {
s->top--;
      data=s->item[s->top+1];
   }
   return data;
}

//To check stack is empty or not
int isempty(int top)
{
if(top==-1)
   return 1;
   else
   return 0;
}

//To  reverse the given string
void reverse(char ch[])
{
int i=0;
   stack s;
   s.top=-1;
   while(ch[i]!='\0')
   {
    push(&s,ch[i]);
      i++;
   }
   while(!isempty(s.top))
   {
    printf("%c",pop(&s));
   }
}

0 Comments