How to Copy a Stack in C++?
Last Updated :
04 Mar, 2024
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++.
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++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack< int > originalStack;
originalStack.push(1);
originalStack.push(2);
originalStack.push(3);
stack< int > newStack = originalStack;
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)
Share your thoughts in the comments
Please Login to comment...