Stack is a common data structure that is used in many circumstances. The most distinct feature is that the element coming first will be popped out last, or in short "first in last out". Besides this, we can always know the size and the top element of a stack in constant time.
If we just look at the properties of a stack, it seems pretty simple. However, the "first in last out" feature turns out to be very powerful, especially when solving some trick programming questions, which can be found in the example questions below.
Some declaration of stacks are shown below:
stack<int> sk1;
stack<double> sk2;
stack<string> sk3;
stack<pair<int, int>> sk4;
if(sk1.size()) {
int first = sk1.top();
sk1.pop();
}
if(!sk2.empty()) {
double d = sk2.top();
sk2.pop();
}
Comments
Post a Comment