C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Data Structure

Reverse a string using stack

In this article, we are going to learn how to reverse a user-defined string using a stack in the data structure?
Submitted by Manu Jemini, on December 19, 2017

A stack is a very important data structure because it can store data in a very practical way. The stack is a linear data structure. Stack array list follows the Last in First Out principle. The element gets to add up at the TOP and deleted from the TOP. (Read more about Stack)

stack

Image source: - https://upload.wikimedia.org/wikipedia/commons/b/b4/Lifo_stack.png

The Below Code has three parts, a Push function, a Pop function and the main function.

The Push function checks whether the stack is full or not. If the stack is full it’s not do anything but if not it takes input from the user and push it to the top of the stack.

The Pop function checks whether the stack is empty, if not then it prints the topmost item and deletes it from the stack.

What happens here is user inputs a string. Every character of that string we pushed in the stack and then we pop every character out. It makes it look like the string is just reversed.

C program to reverse string using stack

#include<stdio.h>
#include<string.h>

//define maximum up to 20
#define MAX 20

int top = -1;
char stack[MAX];

/*Begin of push*/
char push(char item)
{
	if(top == (MAX-1))
		printf("Stack Overflow\n");
	else
		stack[++top] =item;
}
/*End of push*/

/*Begin of pop*/
char pop()
{
	if(top == -1)
		printf("Stack Underflow\n");
	else
		return stack[top--];
}
/*End of pop*/

/*Begin of main*/
main()
{
	char str[20];
	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("Reversed string is : ");
	puts(str);
}
/*End of main*/

Output

Reverse string using stack in c



Liked this article? Do share with your friends :)


COMMENTS