Reverse String using Stack

/* Program to reverse string using stack */
#include<iostream.h>
#include<conio.h>
#define MAX 10
class stack
{
char s[MAX];
int top;
public:
stack()
{
top=-1;
}
void push(char );
char pop();
int isfull();
int isempty();
void display();
void reverse(char *str);
};

void stack:: push(char x)
{
if(isfull()==1)
{
cout<<“\n stack full”;
return;
}
else
{
top++;
s[top]=x;
}
}
char stack:: pop()
{
char ele=’\0′;
if(isempty()==1)
{
cout<<“\n stack empty “;
return ele;
}
else
{
ele=s[top];
top–;
}
return ele;
}
void stack::display()
{
int i;
for(i=top;i>=0;i–)
cout<<“\n”<<s[i];
}
int stack:: isempty()
{
int i=0;
if(top==-1)
i=1;
return i;
}
int stack:: isfull()
{
int i=0;
if(top==MAX)
i=1;
return i;
}
void stack:: reverse(char *str)
{
while(*str)
{
push(*str);
str++;
}
display();
int i=0;
while(isempty()!=1)
{
str[i]=pop();
i++;
}
cout<<“\n str= “<<str;
}

void main()
{
clrscr();
char str[10];
stack st;
cout<<“\n enter String “;
cin>>str;
st.reverse(str);
getch();
}

Leave a Reply