Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%

How to Create a Stack using C++ Arrays

· 2 min read ·Ihsan Arif

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

cpp
 1#include <iostream>
 2#include <iomanip>
 3#define SIZE 100
 4using namespace std;
 5
 6class Stack{
 7    int stack[SIZE];
 8    int atas;
 9public:
10    Stack(){atas=SIZE;}
11    bool empty(){return atas==SIZE;}
12    bool full(){return atas==0;}
13    void push(int value);
14    void pop();
15    int top();
16    int size(){return SIZE-atas;}
17    int getAtas() {return atas;}
18    int *getStack() {return stack;}
19};
20
21void Stack::push(int val){
22    if(full())
23        cout << "Stack is full\n";
24    else{
25        stack[--atas]=val;
26    }
27}
28
29void Stack::pop(){
30    if(empty())
31        cout << "Stack is empty\n";
32    else
33        ++atas;
34}
35
36int Stack::top(){
37    if(empty()){
38        cout << "Stack is empty\n";
39        return 0;
40    }else{
41        return stack[atas];
42    }
43}
44
45ostream& operator<< (ostream &out,Stack &s){
46    if(s.empty())
47        out << "Stack is empty\n";
48    else{
49        for(int i=s.getAtas();i < s.getAtas() + s.size();++i)
50            out << s.getStack()[i] << endl;
51    }
52    return out;
53}
54
55int main(){
56    Stack st;
57    st.push(50);
58    st.push(15);
59    st.push(20);
60    cout << "Stack Awal\n";
61    cout << st;
62    int nilai=st.top();
63    st.pop();
64    cout << "\nHasil pop(): " << nilai << endl;
65    cout << "\nStack Akhir\n";
66    cout << st;
67    return 0;
68}

Function Push()

cpp
1void Stack::push(int val){
2    if(full())
3        cout << "Stack is full\n";
4    else{
5        stack[--atas]=val;
6    }
7}

Function Pop()

cpp
1void Stack::pop(){
2    if(empty())
3        cout << "Stack is empty\n";
4    else
5        ++atas;
6}

Function Top()

cpp
1int Stack::top(){
2    if(empty()){
3        cout << "Stack is empty\n";
4        return 0;
5    }else{
6        return stack[atas];
7    }
8}

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.

IH
Ihsan Arif
Backend engineer & penulis di Santekno. Aktif menulis tentang Go, Laravel, dan arsitektur backend modern.
Follow

💬 Comments