Nov 13, 2018
Stack in C++ STL
Stack / Queue in C++ STL
Stack
The functions associated with stack are:
empty() – Returns whether the stack is empty – Time Complexity : O(1)
size() – Returns the size of the stack – Time Complexity : O(1)
top() – Returns a reference to the top most element of the stack – Time Complexity : O(1)
push(g) – Adds the element g at the top of the stack – Time Complexity : O(1)
pop() – Deletes the top most element of the stack – Time Complexity : O(1)
// CPP program to demonstrate working of STL stack
#include <iostream>
#include <stack>
using namespace std;
void showstack(stack <int> s)
{
while (!s.empty())
{
cout << '\t' << s.top();
s.pop();
}
cout << '\n';
}
int main ()
{
stack <int> s;
s.push(10);
s.push(30);
s.push(20);
s.push(5);
s.push(1);
cout << "The stack is : ";
showstack(s);
cout << "\ns.size() : " << s.size();
cout << "\ns.top() : " << s.top();
cout << "\ns.pop() : ";
s.pop();
showstack(s);
return 0;
}Output:
Queue
Queues are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front.
The functions supported by queue are :
empty()– Returns whether the queue is emptysize()– Returns the size of the queuefront()– Returns a reference to the first element of the queueback()– Returns a reference to the last element of the queuepush(g)– Adds the elementgat the end of the queuepop()– Deletes the first element of the queue
Output:
Last updated