Thursday, May 30, 2013

Contoh Program Menghapus Linked List (Struktur Data)

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<alloc.h>

void buat_baru();
void insert_kiri();
void insert_kanan();
void hapus_depan();
void hapus_belakang();
void tampil();
struct simpul

{
int data;
struct simpul *next;
}
*baru,*awal=NULL, *akhir=NULL, *hapus, *temp;

int main()
{
insert_kiri();
insert_kanan();
insert_kiri();
insert_kiri();
hapus_depan();
hapus_belakang();
tampil();
return 0;
}
void buat_baru()
{
baru=(simpul*)malloc(sizeof(struct simpul));
cout<<"Masukan Data : ";cin>>baru->data;
baru->next=NULL;
}
void insert_kanan()
{
buat_baru();
if(awal==NULL)
{
awal=baru;
}
else
{
akhir->next=baru;
}
akhir=baru;
akhir->next=NULL;
cout<<endl<<endl;
}

void insert_kiri()
{
buat_baru();
if(awal==NULL)
{
awal=baru;
akhir=baru;
akhir->next=NULL;
}
else
{
baru->next=awal;
awal=baru;
}
cout<<endl<<endl;
}
void hapus_depan()
{
if(awal==NULL)
cout<<"Kosong";
else
{
hapus=awal;
awal=awal->next;
free(hapus);
}
cout<<endl<<endl;
}
void hapus_belakang()
{
if(awal==NULL)
cout<<"Kosong";
else if(awal==akhir)
{
hapus=awal;
awal=awal->next;
free(hapus);
}
else
{hapus=awal;
while(hapus->next!=akhir)
hapus=hapus->next;
akhir=hapus;
hapus=akhir->next;
akhir->next=NULL;
free(hapus);
}
cout<<endl<<endl;
}
void tampil()
{
if(awal==NULL)
{
cout<<"kosong";
}
else
{
temp=awal;
while(temp!=NULL)
{
cout<<" Data : "<<temp->data<<"";
temp=temp->next;
}
}
getch();
}

No comments:

Post a Comment

Link