Sitemap

Stack

3 min readOct 2, 2018

--

Stack is a data structure that supports last in first out (LIFO). The implementation is very straightforward and I have attached a simple exercise to illustrate the use of a stack. This calculator implementation can be modified to support more powerful calculation (like multi-digit numbers, brackets, etc).

//simple calculator with stack
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
//implement a stack (for practice)
//pls use STL stack in competition
template<typename Type> class Stack {
private:
Type *elements;
int top_index,max_size;
public:
Stack(int length_input) {
elements=new Type[length_input];
max_size=length_input;
top_index=-1;
}
~Stack() {
delete[] elements;
}
bool push(Type element) {
if(top_index+1>=max_size){
return false;
}
top_index++;
elements[top_index]=element;
return true;
}
bool pop() {
if(top_index<0){
return false;
}
top_index--;
return true;
}
Type top() {
assert(top_index>=0);
return elements[top_index];
}
bool empty() {
return top_index<0;
}
};
//compare precedence of operators
bool precede(char cur, char top) {
if((cur=='*'||cur=='/')&&(top=='+'||top=='-')){
return true;
}
return false;
}
//do one calculation
float operate(char opr, float a, float b) {
if(opr=='+'){
return a+b;
}
else if(opr=='-'){
return b-a;
}
else if(opr=='*'){
return a*b;
}
else{
return b/a;
}
}
//use the top of the two stacks to do a calculation
//push back the result
void calc(Stack<float> &numbers, Stack<char> &operators) {
float a=numbers.top();
numbers.pop();
float b=numbers.top();
numbers.pop();
numbers.push(operate(operators.top(),a,b));
operators.pop();
}
int main() {
int n;
cin>>n;
Stack<float> numbers(n);
Stack<char> operators(n);
string buffer;
cin>>buffer;
int i=0;
while(i<n){
//only supports single digit
if(isdigit(buffer[i])){
numbers.push(buffer[i]-'0');
i++;
}
else{
//if the new operators has higher precedence
//push into stack first
if(operators.empty()||precede(buffer[i],operators.top())){
operators.push(buffer[i]);
i++;
}
else{
calc(numbers,operators);
}
}
}
//clear all calculation
while(!operators.empty()){
calc(numbers,operators);
}
//the last element left in stack is the result
cout<<numbers.top()<<endl;
return 0;
}

A very useful type of stack is the increasing/decreasing stack where elements in the stack are in increasing/decreasing order.

Get Chenglei Si’s stories in your inbox

Join Medium for free to get updates from this writer.

For example, you are given a sequence of numbers. For each number, you need to find the nearest previous number that is less than this current number. We can keep an increasing stack to do this task. Every time, we push the new number into the stack and ensure that the stack is increasing. If there are numbers larger than the current number, we just pop them from the stack.

//strictly increasing stack
//find the nearest previous inputs less than the current input
int main(){
int n, top=-1,t;
cin>>n;
int a[100]; //the stack
for(int i=0;i<n;i++){
cin>>t;
while(top>=0 && a[top]>=t){
top--;
}
if(top==-1){
cout<<t<<" : "<<"no"<<endl;
}
else{
cout<<t<<" : "<<a[top]<<endl;
}
top++;
a[top]=t;
}
}

An example of the application of the decreasing stack is the water pouring problem. You are given n boards with different heights in a row and an infinitely tall board in the end.

pour water on the right side of the 4th board

For each board, we pour water on its right side until the height of the water reaches the height of this board. We need to find the total number of boards that are submerged in water.

This problem is equivalent to finding the first board on the right of each board that is taller (or equal height) as this current board. We can use a decreasing stack to solve this type of problem. Every time when we push a new board into the stack (from left to right), we check if the top board is shorter than the current board. If so, we have found its next taller board and we can just add the number of boards between them and pop that board. We repeat this process until the top board is taller than the current board.

The codes are more explanatory than words.

//simplified
//decreasing stack
typedef pair<int, int> node;
int main(){
int n, ans=0;
cin>>n;
node stack[100];
int top=-1, t;
for(int i=1; i<=n; i++){
cin>>t;
//met the first taller board on the right, process and pop
while(top>=0 && stack[top].second<=t){
ans+=(i-stack[top].first-1);
top--;
}
top++;
stack[top]=node(i, t);
}
//boards left have no taller boards on the right
//use the last infinite board to process
while(top>=0){
ans+=(n+1-stack[top].first-1);
top--;
}
cout<<ans<<endl;
}

(This problem is almost identical to POJ 3250 the bad hair day.) The decreasing stack solves it in O(n) time.

From these two examples, we can see that the increasing/decreasing stack is good at finding the nearest larger or smaller element.

--

--