Anda di halaman 1dari 3

#include <iostream.

h>
#include <conio.h>
#include <stdlib.h>

typedef struct TNode {


int data;
TNode *next;
}data;
TNode *head; //diisi menggunakan head sebagai pointer utama
void init(){ //Fungsi untuk inisialisasi awal linked list
head=NULL; //Untuk pertama kali,head bernilai NULL
}
int IsEmpty(){
if(head==NULL)
return 1;
else
return 0;
}

void insertdepan(int n){


TNode *baru; //Diisi menggunakan baru sebagai pointer TNode
baru=new TNode;
baru->data=n;
baru->next=NULL; //pointer baru->next bernilai NULL
if (IsEmpty()==1){
head=baru;
head->next=NULL;
}
else {
baru->next=head;
head=baru;
}
cout<<"\nData Terisi"<<endl;
}

void tampil(){
TNode *bantu;
bantu=head;
if (IsEmpty()==0){
while(bantu!=NULL){
cout<<bantu->data<<endl;
bantu=bantu->next;
}
}else
cout<<"\nMasih Kosong"<<endl;
}

void insertbelakang(int n){


TNode *baru,*bantu;
baru=new TNode;
baru->data=n;
baru->next=NULL;
if(IsEmpty()==1){
head=baru;
head->next=NULL;
}else{
bantu=head;
while(bantu->next!=NULL){
bantu=bantu->next;
}
bantu->next=baru;
}
cout<<"\nData Terisi"<<endl;
}

void hapusdepan(){
TNode *hapus;
int d;
if (IsEmpty()==0){
if(head!=NULL){
hapus=head;
d=hapus->data;
head=hapus->next;
delete hapus;
}
cout<<d<<"Terhapus"<<endl;
}else cout<<"\nMasih Kosong"<<endl;
}

main(){
int pil;
do{
int n;
cout<<"1. Insert Depan "<<endl;
cout<<"2. Insert Belakang " <<endl;
cout<<"3. Display"<<endl;
cout<<"4. Hapus"<<endl;
cout<<"5. Exit"<<endl;
cout<<"\nMasukan Pilihan (1-5): ";
cin>>pil;

switch(pil){
case 1:
cout<<"Masukan Data : "; cin>>n;
IsEmpty();
insertdepan(n);
break;
case 2:
cout<<"Masukan Data : "; cin>>n;
IsEmpty();
insertbelakang(n);
break;
case 3:
IsEmpty();
tampil();
break;
case 4:
IsEmpty();
hapusdepan();
break;
}
}while(pil!=5);
getch();
return 0;
}

Anda mungkin juga menyukai