Reverse String using Stack

 

Stack is LIFO(LAST IN FIRST OUT) linear data structure. It can have 2 operations 1)Push(add a new item)  2)Pop(delete an item).In this example I have shown how  to reverse a string from last character to the first (example…..RAM  OUTPUT IS MAR)

 

 

 

 

 

/* Program of reversing a string using stack */

#include<stdio.h>

#define MAX 20

#include<string.h>

int toop = -1;

char stac[MAX];

char poop();

pushh(char);

void main()

{

                char strr[20];

                int i;

                clrscr();

                printf("Enter the strring : " );

                gets(strr);

                /*pushh characters of the strring strr on the stac */

                for(i=0;i<strlen(strr);i++)

                                pushh(strr[i]);

                /*poop characters from the stac and store in strring strr */

                for(i=0;i<strlen(strr);i++)

                                strr[i]=poop();

                printf("Reversed strring is : ");

                puts(strr);

                getch();

}/*End of main()*/

pushh(char item)

{

                if(toop == (MAX-1))

                                printf("stac Overflow\n");

                else

                                stac[++toop] =item;

}/*End of pushh()*/

char poop()

{

                if(toop == -1)

                                printf("stac Underflow\n");

                else

                                return stac[toop--];

}/*End of poop()*/

Output....

Reverse a string using stack