Pemrograman

How to Create a Double Linked List using C++

Double Linked List is a linked list that uses just a pointer variable to store a lot of data using the linked list method, a list of contents that are interconnected.

OK, Santekno will provide an implementation of Double Linked List using the C++ language. The most important thing in making a Double Linked List is that we will create a link that can later be connected to each other so that in order to be connected to each other we need several functions that can operate it, such as, insert front, insert back, insert in the middle, delete, size, and others.

The Linked List that Santekno will create applies 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 DLL, or an abbreviation for Double Linked List.

Functions to be created

  • Created make() Function Node
  • Add Node behind push_back()
  • Add Node in front of push_front()
  • Add Nodes after n push_after()
  • Search Node find()
  • Searches for Nodes before n find_before()
  • Delete Node n del()
  • Prints the linked list print()
  • Play Programs

SLL Class Program Code

#include <iostream>
#include <list>

using namespace std;
typedef list<int> LI;

class DLL{
    LI dt;
public:
    int isEmpty(){ return dt.empty();}
    void push_back(int val);
    void push_front(int val);
    void push_after(int val,int after);
    LI::iterator find(int val);
    void del(int val);
    void print();
};

void DLL::print(){
    LI::iterator it;
    for(it=dt.begin();it!=dt.end();++it)
        cout << (*it) << "->";
    cout << "NULL" << endl;
}

LI::iterator DLL::find(int val){
    LI::iterator it;
    for(it=dt.begin();it!=dt.end();++it)
        if((*it) == val) return it;
    return it;
}
void DLL::push_back(int val){
  dt.push_back(val);
}

void DLL::push_front(int val){
  dt.push_front(val);
}

void DLL::push_after(int val,int after){
    LI::iterator it=find(after);
    if(it!=dt.end()){
        ++it;
        dt.insert(it,val);
    }
}
void DLL::del(int val){
    LI::iterator it=find(val);
    if(it!=dt.end()) dt.erase(it);
}

int main(){
    DLL list;
    list.push_back(10);
    list.push_front(20);
    list.push_front(30);
    list.push_after(10,50);
    list.del(20);
    list.print();
    return 0;
}

Output

comments powered by Disqus