×

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance.

Here is a straightforward stack-based technique for reversing strings.

Algorithm:

1) Make a stack that is empty.

2) Push each character in the string to the stack one at a time.

3) Remove each character from the stack one at a time, then add them back to the string.

C Program:

// A stack-based C program to reverse a given string
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>


// A stack-representing structure
struct Stack
{
	int top;
	unsigned capacity1;
	char* arr;
};


// Stack creation function with provided capacity
// It starts off with a stack size of 0.
struct Stack* createtheStack ( unsigned capacity1 )
{
	struct Stack* stack = ( struct Stack* ) malloc( sizeof( struct Stack ) );
	stack -> capacity1 = capacity1;
	stack -> top = -1;
	stack -> arr = ( char* ) malloc( stack -> capacity1 * sizeof ( char ) );
	return stack;
}


// When top equals the last index, a stack is considered full.
int isitFull ( struct Stack* stack )
{ return stack -> top == stack -> capacity1 - 1; }


// Whenever top equals -1, the stack is empty.
int isitEmpty ( struct Stack* stack )
{ return stack -> top == -1; }


// Adds a new item to the stack.
// Top is raised by 1 in the code.
void push ( struct Stack* stack, char item1 )
{
	if ( isitFull ( stack ) )
		return;
	stack -> arr [++stack -> top] = item1;
}


// Function to delete an item from the stack
// It lowers the top by one.
char pop ( struct Stack* stack )
{
	if ( isitEmpty ( stack ) )
		return INT_MIN;
	return stack -> arr [ stack->top-- ];
}


// A method that uses stacks to reverse strings
void reverse ( char str [] )
{
	// Form a stack with a size equal to the string's length.
	int no = strlen (str);
	struct Stack* stack = createtheStack (no);


	// Push the string's characters all into a stack.
	int index;
	for ( index = 0; index < no; index++ )
		push ( stack, str [ index ] );


	// Pop every character off the string and then return them to str.
	for ( index = 0; index < no; index++ )
		str [index] = pop (stack);
}


// Driver code for testing the above features
int main ()
{
	char str [] = "tutorialandexample";


	reverse (str);
	printf ( "The reversed string will be '%s'.", str );


	return 0;
}

C++ Program:

// A stack-based C++ program to reverse a given string
#include <bits/stdc++.h>
using namespace std;


// A stack-representing structure
class Stack
{
	public:
	int top;
	unsigned capacity1;
	char* arr;
};
// Stack creation function with provided capacity
// It starts off with a stack size of 0.
Stack* createtheStack ( unsigned capacity1 )
{
	Stack* stack = new Stack ();
	stack -> capacity1 = capacity1;
	stack -> top = -1;
	stack -> arr = new char [ (stack -> capacity1 * sizeof ( char ) ) ];
	return stack;
}


// When top equals the last index, a stack is considered full.
int isitFull ( Stack* stack )
{ return stack -> top == stack -> capacity1 - 1; }


// Whenever top equals -1, the stack is empty.
int isitEmpty ( Stack* stack )
{ return stack -> top == -1; }


// Adds a new item to the stack.
// Top is raised by 1 in the code.
void push ( Stack* stack, char item1 )
{
	if ( isitFull (stack) )
		return;
	stack -> arr [ ++stack -> top ] = item1;
}


// Function to delete an item from the stack
// It lowers the top by one.
char pop ( Stack* stack )
{
	if ( isitEmpty (stack) )
		return -1;
	return stack -> arr [ stack -> top-- ];
}


// A method that uses stacks to reverse string
void reverse ( char str [] )
{
	// Form a stack with a size equal to the string's length.
	int no = strlen ( str );
	Stack* stack = createtheStack (no);


	// Push the string's characters all into a stack.
	int index;
	for ( index = 0; index < no; index++ )
		push ( stack, str [index] );
	// Pop every character off the string and then return them to str.
	for ( index = 0; index < no; index++ )
		str [index] = pop (stack);
}


// Driver code for testing the above features
int main ()
{
	char str [] = "tutorialandexample";


	reverse (str);
	cout << "The reversed string will be " << str;


	return 0;
}

Output:

The reversed string will be elpmaxednalairotut

Time Complexity: O(n)

Space Complexity: O(n)

[ where n is the number of characters on the stack ]


Related Topics

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

Default arguments in C++

Arguments in a function are defined as the values supplied when the function is called. The source is the values supplied, and the destination is the receiving function. Let us...

3 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

C++ Multimap

Definition: In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and...

4 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.