Stack in C++
The stack adapter follows the Last In, First Out (LIFO) principle, and the insertion and removal of elements can be done only from the top of the queue container.
The following are the key operations of the stack:
push(elm)
: Insert the element elm at the top.pop()
: Removes the top element.top()
: Returns a reference to the top element.empty()
: Checks whether the stack is empty.size()
: Returns the number of elements.
Example of Stack
The below example demonstrates the usage of key operations in stack adapter in C++.
C++
// C++ program to demonstrate the usage of key operations in // stack adapter in C++. #include <iostream> #include <stack> using namespace std; int main() { // Declaring an instance of the stack adapter with stack< int > myStack; // Push elements onto the stack myStack.push(10); myStack.push(20); myStack.push(30); // print size of stack cout << "Size of stack is: " << myStack.size() << endl; // Pop elements from the stack until it's empty cout << "Elements in a stack are: " ; while (!myStack.empty()) { // Display the top element cout << myStack.top() << " " ; // Remove the top element myStack.pop(); } return 0; } |
Output
Size of stack is: 3 Elements in a stack are: 30 20 10
Time Complexity: O(n)
Auxilliary Space: O(1)
Container Adapter in C++
The container adapters are a part of the C++ standard library that gives us a way to modify or adapt existing container classes to suit specific needs or requirements. In this article, we will learn about container adapters in C++.
Contact Us