Thursday, May 30, 2013

Contoh Program Menu Linked List, Insert Kiri, Insert Kanan, Hapus Depan, Hapus Belakang (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()
{
int pilihan;
awal:
printf("\nMENU SINGLE LINKED LIST\n");
printf("1. Insert Kiri\n");
printf("2. Insert Kanan\n");
printf("3. Hapus Depan\n");
printf("4. Hapus Belakang\n");
printf("5. Tampilkan\n");
printf("6. Selesai\n");

printf("Pilihan Anda : ");
scanf("%d",&pilihan);
if (pilihan==1)
{
insert_kiri();
tampil();
}
if(pilihan==2)
{
insert_kanan();
tampil();
}
if(pilihan==3)
{
hapus_depan();
tampil();
}
if(pilihan==4)
{
hapus_belakang();
tampil();
}
if(pilihan==5)
{
tampil();
}
if(pilihan==6)
{
return 0;
}
goto awal;
}
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();
}

3 comments:

Link