Tuesday 21 April 2009

Contoh Program Menu Linked List

#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
struct node{
int info;
struct node *next;
};
typedef struct node *simpul;

void main()
{
simpul baru, head=NULL, tail=NULL, temp;
int pilih;
do
{
printf("MENU\n");
printf("1. Insert\n");
printf("2. View\n");
printf("3. Search\n");
printf("4. Delete\n");
printf("PILIH: ");
scanf("%d", &pilih);
switch(pilih)
{
case 1:
int data;
printf("Data Masuk: ");
scanf("%i", &data);
baru = (simpul) malloc(sizeof (struct node));
baru->info = data;
baru->next = NULL; //tidak menuju simpul mana2
if (head == NULL) //khusus simpul pertama LL
{
head = baru; //pointer head, tail, baru sama
tail = baru;
}
else //untuk simpul2 berikutnya
{
tail->next = baru; //sambungkan di belakang
tail = baru;
}
break;
case 2:
temp = head; //tampilkan mulai dr depan
while(temp!=NULL) //ulangi sampai temp bernilai NULL
{
printf("%i ", temp->info);
temp = temp->next; //geser temp ke belakang
}
printf("\n");
break;
case 3:
int cari;
printf("Cari Angka: ");
scanf("%i", &cari);
temp = head;
while((temp!=NULL)&&(temp->info!=cari))
{
temp = temp->next;
}
if(temp != NULL && temp->info == cari)
printf("Data Ditemukan");
else //if(temp == NULL)
printf("Data Tidak Ditemukan");
printf("\n");
break;
case 4:
int hapus;
char jwb;
simpul prev = NULL;
printf("Hapus Angka: ");
scanf("%i", &hapus);
temp = head;
while((temp!=NULL)&&(temp->info!=hapus))
{
//prev selalu berada 1 simpul di belakang temp
prev = temp;
temp = temp->next;
}
if(temp != NULL && temp->info == hapus)
{
printf("Yakin Dihapus? (y/t)");
flushall();
jwb=getch();
if(jwb == 'y')
{
//jika hapus simpul di tengah
if(temp->next != NULL && temp != head)
prev->next = temp->next;
//jika hapus di depan dan tinggal 1 simpul
else if (temp == head && head->next == NULL)
{
head = NULL;
}
//jika hapus di depan tapi masih ada simpul berikutnya
else if (temp == head && head->next != NULL)
{
head = head->next;
}
//jika hapus di belakang
else if (temp->next == NULL)
{
prev->next = NULL;
tail = prev;
}
free(temp); //hapus dr memori
}
else
printf("Batal Dihapus");
}
else
printf("Data Tidak Ditemukan");
printf("\n");
break;
}
}while (pilih!=5);
}

No comments:

Post a Comment