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)


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


//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");
		stack[++top] =item;
/*End of push*/

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

/*Begin of main*/
	char str[20];
	int i;
	printf("Enter the string : " );
	printf("Reversed string is : ");
/*End of main*/


Reverse string using stack in c

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.