![]() |
VOOZH | about |
Stack container follows LIFO (Last In First Out) order of insertion and deletion. It means that most recently inserted element is removed first and the first inserted element will be removed last. This is done by inserting and deleting elements at only one end of the stack which is generally called the top of the stack.
Top element: 5 Top element after pop: 10
Stack is defined as std::stack class template inside the <stack> header file.
stack<T> st;
where,
Here are the basic operations that can be performed on a stack:
In stack, new elements can only be inserted at the top of the stack by using push() method.
Only the top element of the stack can be accessed using top() method.
40
Note: top() is used to only view the topmost element of the stack not print it.
In stack, only the top element of the stack can be deleted by using pop() method in one operation.
30 20 10
This checks whether the stack is empty. It returns true if the stack has no elements, otherwise, it returns false.
Stack is empty Stack is not empty. Top element: 100
The size() function in a stack returns the number of elements currently in the stack. It helps to determine how many items are stored without modifying the stack.
Size of stack: 2 Size of stack:1
A stack cannot be directly traversed, but by creating a copy and repeatedly accessing and popping the top element, we can traverse it without modifying the original stack.
40 30 20 10
Explanation: Pseudo-traversal is done by creating a copy of the "st" to avoid modifying the original stack. The while loop prints and removes elements from temp using "top()" and "pop()" until the stack becomes empty.