Simple single linked list with delete algorithm in c

 #include <stdio.h>

#include <stdlib.h>

typedef struct element

    int data;

    struct element * next;

}element;

element * createdelement(int data)

{

    element * buatelement = NULL;

    buatelement = (element*)malloc(sizeof(element));

    buatelement->data  = data;

    buatelement->next = NULL;

}

void adddepan(int data, element ** g)

{

    element * newlist = createdelement(data);

    newlist->next = (*g);

    (*g) = newlist;

}

void addtengah(int data,int cari, element * g)

{

    element * newlist = createdelement(data);

    element * temp  = NULL;

    temp = g;

    g = newlist;

    while(temp->data != cari)

    {

        temp = temp->next;

    }

    newlist->next = temp->next;

    temp->next = newlist;

}

void addbelakang(int data,element * g)

{

    element * newlist  = createdelement(data);

    element * temp = NULL;

    temp  = g;

    while(temp->next != NULL)

    {

        temp = temp->next;

        

    }

    newlist->next  = temp->next;

    temp->next = newlist;

}

void print(element * g)

{

    element * temp = g;

    do

    {

        printf("%d",temp->data);

        temp = temp->next;

    }while(temp != NULL);

    

}

void deldepan(element ** g)

{

    if(g != NULL)

    {

    element * hapus = (*g);

    (*g) = hapus->next;

    hapus->next = NULL;

    free(hapus);

    }else

    {

        printf("kosong");

    }

    

}

void deltengah(int cari,element *g)

{

    element * prev = g;

    

    element * temp = g;

   

    while(temp->data != cari)

    {

        prev = temp;

        temp= temp->next;

         

    }

    prev->next = temp->next;

    temp->next = NULL;

    free(temp);

}

void delbelakang(element * g)

{

    element *  hapus = g;

    element * prev = g;

    while(hapus->next != NULL)

    {

        prev = hapus;

        hapus = hapus->next;

    }

    prev->next = hapus->next;

    hapus->next = NULL;

    free(hapus);

    

}

int main()

{

    element * g = createdelement(6);

    adddepan(10,&g);

    addtengah(11,6,g);

    addbelakang(9,g);

    print(g);

    printf("\n");

    deldepan(&g);

    deltengah(11,g);

    delbelakang(g);

    print(g);

}


Komentar

Postingan populer dari blog ini

Pentingnya Mendapatkan Sertifikasi di Bidang IT/Sebagai Programmer

Pengantar Java Swing Bagian 1

Pengenalan UML