Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end and (top) an element is removed from that end only.
stack::swap()
This function is used to swap the contents of one stack with another stack of same type but the size may vary. Syntax :
stackname1.swap(stackname2)
Parameters: The name of the stack with which the contents have to be swapped. Result: All the elements of the 2 stack are swapped. Examples:
contents of the stack from top to bottom are
Input : mystack1 = {4, 3, 2, 1}
mystack2 = {9, 7 ,5, 3}
mystack1.swap(mystack2);
Output : mystack1 = 9, 7, 5, 3
mystack2 = 4, 3, 2, 1
Input : mystack1 = {7, 5, 3, 1}
mystack2 = {8, 6, 4, 2}
mystack1.swap(mystack2);
Output : mystack1 = 8, 6, 4, 2
mystack2 = 7, 5, 3, 1
Note: In stack container, the elements are printed in reverse order because the top is printed first then moving on to other elements.
CPP
#include <stack>
#include <iostream>
using namespace std;
int main()
{
stack< int > mystack1;
stack< int > mystack2;
mystack1.push(1);
mystack1.push(2);
mystack1.push(3);
mystack1.push(4);
mystack2.push(3);
mystack2.push(5);
mystack2.push(7);
mystack2.push(9);
mystack1.swap(mystack2);
cout<< "mystack1 = " ;
while (!mystack1.empty()) {
cout<<mystack1.top()<< " " ;
mystack1.pop();
}
cout<<endl<< "mystack2 = " ;
while (!mystack2.empty()) {
cout<<mystack2.top()<< " " ;
mystack2.pop();
}
return 0;
}
|
Output:
mystack1 = 9 7 5 3
mystack2 = 4 3 2 1
Time Complexity: O(1)
Auxiliary Space: O(n)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Jun, 2022
Like Article
Save Article