Sabtu, 13 April 2013

Single linked list


Look at this !

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

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



void buat_baru();
void insert_kiri();
void insert_kanan();
void hapus_depan();
void hapus_belakang();
void tampil();
int main()
{
int k;
cout<<endl;

cout<<"=====Menu single linked list====="<<endl;
cout<<"By Bella yulianita"<<endl;
cout<<"1.insert kiri"<<endl;
cout<<"2.insert kanan"<<endl;
cout<<"3.hapus depan"<<endl;
cout<<"4.hapus belakang"<<endl;
cout<<"5.tampilkan"<<endl;
cout<<"6.Selesai"<<endl;
cout<<endl;
a:
cout<<"Masukkan pilihan anda(1,2,3,4,5,6):";
cin>>k;
if(k==1)
{
insert_kiri();
goto a;
}
if(k==2)
{
insert_kanan();
goto a;
}
if(k==3)
{
hapus_depan();
goto a;
}
if(k==4)
{
hapus_belakang();
goto a;
}
if(k==5)
{
tampil();
goto a;
}
if(k==6)
{
return 0;
}


}
void buat_baru()
{
baru=(simpul*)malloc(sizeof(struct simpul));
cout<<"masukkan 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<<endl;
temp=temp->next;
}
}
getch();
}
Outputnya:

Created by Bella Yulianita

0 komentar:

Posting Komentar

© Bella Yulianita 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis