Pemrograman

How to Create a Stack using Double Linked List

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.

Implementing Stack using a DLL is also the same, the rules are not eliminated, but the most different thing is that if you use a DLL it is looser regarding data allocation, because the data structure is Double Linked List unlimited although it can be limited.

Source Code Stack

#include <iostream>
#include <list>

using namespace std;

class Stack{
    list<int> stack;
    list<int>::iterator atas;
public:
    Stack(){atas=stack.begin();}
    bool empty(){return (atas==stack.end());}
    int size(){ return stack.size();}
    void push(int nilai);
    void pop();
    int top();
    list<int>::iterator getAtas() {return atas;}
    list<int> getStack() {return stack;}
};

Function Push()

void Stack::push(int val){
    stack.push_front(val);
    atas=stack.begin();
}

Function Pop()

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

Function Top()

int Stack::top(){
    return (*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