Pemrograman

How to Create a Stack using C++ Arrays

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.

Stack Class Code

#include <iostream>
#include <iomanip>
#define SIZE 100
using namespace std;

class Stack{
    int stack[SIZE];
    int atas;
public:
    Stack(){atas=SIZE;}
    bool empty(){return atas==SIZE;}
    bool full(){return atas==0;}
    void push(int value);
    void pop();
    int top();
    int size(){return SIZE-atas;}
    int getAtas() {return atas;}
    int *getStack() {return stack;}
};

void Stack::push(int val){
    if(full())
        cout << "Stack is full\n";
    else{
        stack[--atas]=val;
    }
}

void Stack::pop(){
    if(empty())
        cout << "Stack is empty\n";
    else
        ++atas;
}

int Stack::top(){
    if(empty()){
        cout << "Stack is empty\n";
        return 0;
    }else{
        return stack[atas];
    }
}

ostream& operator<< (ostream &out,Stack &s){
    if(s.empty())
        out << "Stack is empty\n";
    else{
        for(int i=s.getAtas();i < s.getAtas() + s.size();++i)
            out << s.getStack()[i] << endl;
    }
    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;
}

Function Push()

void Stack::push(int val){
    if(full())
        cout << "Stack is full\n";
    else{
        stack[--atas]=val;
    }
}

Function Pop()

void Stack::pop(){
    if(empty())
        cout << "Stack is empty\n";
    else
        ++atas;
}

Function Top()

int Stack::top(){
    if(empty()){
        cout << "Stack is empty\n";
        return 0;
    }else{
        return stack[atas];
    }
}

This class has several methods or functions that comply with the properties and rules of Stack. Such as Push, Pop, Top and Full. Push is saving data into the stack. then Pop is taking the top data from the Stack while Top is looking at the top data contents of a Stack.

comments powered by Disqus