Reverse a string using stack

Problem Statement: Reverse a string using stack in C.
Here we have used an array to implement the stack.

/*Reverse a string using stack. Implement your own stack*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define MAX 20

int top = -1;
char stack[MAX];
char pop();
void push(char);

int main()
{
        char str[20];
        unsigned int i;
        printf("Enter the string : " );
        gets(str);
        for(i=0;i<strlen(str);i++)
                push(str[i]);
        for(i=0;i<strlen(str);i++)
                str[i]=pop();
        printf("\nReversed string is : ");
        puts(str);

        return 0;

}

void push(char item)
{
        if(top == (MAX-1))
        {
                printf("\nStack Overflow\n");
                return;
        }
        stack[++top] =item;
}

char pop()
{
        if(top == -1)
        {
                printf("\nStack Underflow\n");
                exit(1);
        }
        return stack[top--];
}
$gcc stack.c
$ ./a.out
Enter the string : mycomputerknowledge
Reversed string is : egdelwonkretupmocym
$

also see

C Programming language
Go Programming language
Linked List Array
Simplification Queue
DBMS Reasoning
Aptitude HTML
Previous articleRearrange an array such that arr[i] = i in C
Next articleFirst C Program

LEAVE A REPLY

Please enter your comment!
Please enter your name here