Problems
Let’s re-implement Beginner Coder problem #1102 using the STL stack.
The stack data structure can be implemented using the STL, and in practice, this is much more convenient.
Declaring a Stack
You can declare a stack as follows:
#include <stack>
using namespace std;
stack<int> s;
In the code above, <int> indicates the data type stored in the stack, and s is the name of the stack.
(The stack name can be chosen freely.)
If you declare it like this:
stack<char> s2;
then s2 becomes a stack that stores char values.
Commonly Used Stack Methods
After declaring a stack, the main methods you will use are the following:
Function 1: empty()
Usage example:
if (s.empty() == true) ...
The empty() function is a boolean function that returns true or false.
Returns
trueif the stack is emptyReturns
falseif the stack is not empty
Function 2: push()
Usage example:
s.push(7);
This inserts 7 at the top of the stack s.
In other words, 7 becomes the top element of s.
int k = 7;
s.push(k);
This also inserts 7 at the top of the stack.
Function 3: pop()
Usage example:
s.pop();
This removes the element at the top of the stack.
It only removes the element and does not return its value.
If pop() is called when the stack is empty, a runtime error occurs.
Therefore, always make it a habit to call empty() first to check whether the stack is empty before calling pop().
Function 4: top()
Usage example:
if (s.top() == 7) ...
// or
int t = s.top();
The top() function returns the value of the element at the top of the stack.
It only tells you the value and does not remove the element.
Just like pop(), calling top() on an empty stack causes a runtime error.
So always check whether the stack is empty using empty() before calling top().
Function 5: size()
Usage example:
if (s.size() == 0) ...
// or
int sz = s.size();
The size() function returns the number of elements in the stack.
If the stack is empty, size() returns 0.
Re-implementing Problem #1102
Now, using the five functions above, re-implement problem #1102.
< Processing Rules >
The given commands are as follows:
"i a": Insert the integerainto the stack.
(ais a natural number less than or equal to 10,000.)"o": Remove the top element from the stack and output it.
If the stack is empty, output"empty"."c": Output the number of elements currently stored in the stack.
Input
The first line contains N. N is the number of commands given. (1≤N≤100)
From the second line to the (N+1)-th line, N commands are given, one per line.
Output
Print the output value for each command, one per line.
Cases where there is no output content will not be given.
Example
7
i 7
i 5
c
o
o
o
c
2
5
7
empty
0