×

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

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 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.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.