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

How to Use a Single Linked List Using C++

· 2 min read ·Ihsan Arif

Linked List is a form of data structure, containing a collection of data (nodes) that are arranged sequentially, interconnected, dynamic and limited. Meanwhile Single Linked List is a linked list which 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 Single Linked List using C++ language. The most important thing in making a Single Linked List is that we will create a link which can then 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 SSL, or an abbreviation for Single 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

cpp
 1#include <utility>
 2#include <iostream>
 3#include <forward_list>
 4#include <string>
 5
 6using namespace std;
 7
 8typedef par<string, float> P;
 9typedef forward_list<P> SLLP;
10
11class SLL{
12    SLLP dt;
13    void push_front(string nim,float ipk);
14    void push_back(string nim, float ipk);
15    void push_after(string nim,float ipk, string after);
16    void del(string nim);
17    SLLP::iterator find(string nim);
18    void print();
19};
20
21void SLL::print(){
22    SLLP::iterator it;
23    for(it=dt.begin();it!=dt.end();++it){
24        cout << "(" << it->first << "," << it->second << ")->";
25    }
26    cout << "NULL"<< endl;
27}
28
29void SLL::push_front(string nim, float ipk){
30    P t=make_pair(nim,ipk);
31    dt.push_front(t);
32}
33void SLL::push_back(string nim,float ipk){
34    P t=make_pair(nim,ipk);
35
36    if(dt.empty())
37        dt.push_front(t);
38    else{
39        SLLP::iterator before=dt.begin();
40        SLLP::iterator it=dt.begin();
41        for(;it!=dt.end();before=it,++it);
42        dt.insert_after(before,t);
43    }
44}
45
46int main(){
47    SLL list;
48    list.make();
49    list.push_back(100); list.push_back(50);
50    list.push_front(75); list.print();
51    list.push_after(35,100); list.print();
52    list.del(50); list.print();
53    return 0;
54}

Output

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

💬 Comments