Pemrograman

How to Create a Stack Using the Standard Template Library

Stack is a data structure that provides data like a stack in a glass, so if data is put into a glass the first one will be the last to be taken, then this data structure adheres to the LIFO (Last In First Out) rule. ). The meaning of LIFO is that the last person in will be the first to leave.

The Stack that Santekno will create implements the OOP (Object Oriented Programming) system so that it is easier to understand. In OOP we have to create a class which we will call Stack.

As previously posted, Stack uses Arrays, implementing Stack using STL is easier because the C program has created a library for the stack so we don’t need to create special functions, we just include the stack and then all the properties of the stack already exist.

Source Code

#include <iostream>
#include <stack>
typedef stack<int> Stack;

ostream& operator<< (ostream &out, Stack &s){
    if(s.empty())
        out << "Stack is empty\n";
    else{
        while(!(s.empty())){
            int t = s.top();
            out << t << endl;
            s.pop();
        }
    }
    return out;
}

int main(){
    Stack st;
    st.push(50);
    st.push(15);
    st.push(20);
    cout << "Stack Awal\n";
    cout << st;
    int nilai=st.top();
    st.pop();
    cout << "\nHasil pop(): " << nilai << endl;
    cout << "\nStack Akhir\n";
    cout << st;
    return 0;
}
comments powered by Disqus