Copying a Stack to Another in C++
To copy a std::stack, we can simply use the copy constructor or copy assignment operator of std::stack that takes another stack as a parameter and creates a new stack with the same elements.
Syntax
stack<type> myStack2(myStack1); // copy constructor
myStack2 = myStack1 // copy assignment operator
C++ Program to Copy a Stack
C++
// C++ program to illustrate how to copy a stack #include <iostream> #include <stack> using namespace std; int main() { // Declaring a stack of integers stack< int > originalStack; // Pushing integers into the original stack originalStack.push(1); originalStack.push(2); originalStack.push(3); // Copying the original stack to a new stack stack< int > newStack = originalStack; // Checking if the new stack is empty if (newStack.empty()) { cout << "New stack is empty." << endl; } else { cout << "New stack is not empty." << endl; } return 0; } |
Output
New stack is not empty.
Time complexity: O(N), where n is the number of elements in the stack.
Auxiliary space: O(N)
How to Copy a Stack in C++?
In C++, stacks are a type of container adaptor with a LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. In this article, we are going to discuss how to copy a stack in C++.
Contact Us