Contoh Penerapan Single Linked List dalam Bahasa C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct element
{
int id;
char namaproduk[10];
int hargaproduk;
struct element * next;
}element;
element * buatlist(int id,char namaproduk[10],int hargaproduk)
{
element *elementBaru = NULL; //masih kosong
elementBaru = (element*) malloc (sizeof(element));
elementBaru -> id = id;
strcpy(elementBaru->namaproduk,namaproduk);
elementBaru->hargaproduk = hargaproduk;
elementBaru -> next = NULL;
return elementBaru;
}
void depan(int id,char namaproduk[10],int hargaproduk,element **listaku)
{
element * newlist = buatlist(id,namaproduk,hargaproduk);
newlist -> next = (*listaku);
(*listaku) = (newlist);
}
void belakang(int id,char namaproduk[10],int hargaproduk,element *listaku)
{
element * newlist = buatlist(id,namaproduk,hargaproduk);
element * temp = NULL;
temp = listaku;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next= newlist;
}
void tengah(int id,char namaproduk[10],int hargaproduk,element *listaku)
{
element * newlist = buatlist(id,namaproduk,hargaproduk);
element * temp = NULL;
temp = (listaku);
(listaku) = newlist;
while(temp->id != 8)
{
temp = temp->next;
}
newlist -> next = temp->next;
temp -> next = newlist;
}
void cetak(element * listaku)
{
element * temp = listaku;
do
{
printf("Produk %d\n%s\n%d\n",temp->id,temp->namaproduk, temp->hargaproduk);
temp = temp ->next;
}
while(temp!=NULL);
}
void deletawal(element ** listaku)
{
if(listaku !=NULL)
{
element * hapus = (*listaku);
(*listaku) = hapus->next;
hapus->next = NULL;
free(hapus);
}
else{
printf("error");
}
}
void delettengah(element * listaku,int a)
{
element *hapus;
element *prev;
hapus = (listaku);
prev = (listaku);
a=2;
if(listaku != NULL)
{
while(hapus->id != a)
{
prev = hapus;
hapus = hapus->next;
}
prev->next = hapus -> next;
hapus->next = NULL;
free(hapus);
}
else
{
printf("List Kosong");
}
}
void deleteakhir(element *listaku)
{
element *hapus;
element *prev;
hapus = (listaku);
prev = (listaku);
if(listaku != NULL)
{
while(hapus->next != NULL)
{
prev = hapus;
hapus = hapus->next;
}
prev->next = hapus -> next;
hapus->next = NULL;
free(hapus);
}
else
{
printf("List Kosong");
}
}
int main()
{
int a = 2;
element * mainutama;
mainutama = buatlist(8,"Mie Instan",3200);
depan(2,"Sabun Cuci",23200,&mainutama);
belakang(10,"Kecap",8700,mainutama);
depan(1,"Mie Instan",3200,&mainutama);
tengah(9,"kopi",7600,mainutama);
delettengah(mainutama,a);
deletawal(&mainutama);
deleteakhir(mainutama);
cetak(mainutama);
}
Komentar
Posting Komentar