Reverse a Stack in C++
A stack is a linear data structure that follows the Last In First Out (LIFO) principle, where the last element added to the stack is the first one to be removed. In other words, the element that is placed last on the top of the stack is the first one to be removed. This makes stacks a useful data structure for implementing algorithms such as undo and redo functions, backtracking, and expression evaluation. However, in some cases, it may be necessary to reverse the order of the elements in a stack. In this article, we will discuss how to reverse a stack in C++.
Before we dive into the implementation of reversing a stack in C++, let's first understand the basic structure of a stack. A stack is implemented using an array or a linked list. The array implementation of a stack is simpler and more efficient, while the linked list implementation allows for dynamic memory allocation. In this article, we will be using the array implementation of a stack.
The basic operations that can be performed on a stack are push, pop, top, and isEmpty. The push operation is used to add an element to the top of the stack, while the pop operation is used to remove the top element from the stack. The top operation returns the top element of the stack without removing it, and the isEmpty operation returns true if the stack is empty, and false otherwise.
To reverse a stack, we can use the following algorithm:
- Create an empty stack called tempStack.
- While the original stack is not empty, pop the top element from the original stack and push it onto the tempStack.
- Once all elements have been popped from the original stack and pushed onto the tempStack, the original stack will be reversed.
The implementation of this algorithm in C++ is as follows:
#include <iostream>
using namespace std;
class Stack {
private:
int top;
int size;
int *arr;
public:
Stack(int size) {
this->size = size;
top = -1;
arr = new int[size];
}
// Push operation
void push(int value) {
if(top == size-1)
{
cout << "Stack is full." << endl;
return;
}
top++;
arr[top] = value;
}
// Pop operation
int pop() {
if(top == -1)
{
cout << "Stack is empty." << endl;
return -1;
}
int value = arr[top];
top--;
return value;
}
// Top operation
int getTop() {
if(top == -1) {
cout << "Stack is empty." << endl;
return -1;
}
return arr[top];
}
// isEmpty operation
bool isEmpty() {
return (top == -1);
}
// Reverse stack
void reverseStack(Stack &original) {
Stack tempStack(original.size);
while(!original.isEmpty())
{
int value = original.pop();
tempStack.push(value);
}
original = tempStack;
}
};
int main() {
Stack original(5);
original.push(1