Selasa, 27 April 2010

Double Linked List

Penggunaan Fungsi Push depan, push belakang, pop depan, pop belakang

#include <stdio.h>
#include <stdlib.h>

struct data
{
int angka;
struct data *next, *prev;
}*head = NULL, *tail = NULL, *curr = NULL;

void clear()
{
for(int c=0; c<25; c++)
printf("\n");
}

void push_depan(int angka)
{
curr = (struct data*)malloc(sizeof(struct data));
curr->angka = angka;
curr->next = curr->prev = NULL;

if(head==NULL)
{
head = tail = curr;
}
else
{
head->prev = curr;
curr->next = head;
head = curr;
}
}

void push_belakang(int angka)
{
curr = (struct data*)malloc(sizeof(struct data));
curr->angka = angka;
curr->next = curr->prev = NULL;

if(head==NULL)
{
head = tail = curr;
}
else
{
tail->next = curr;
curr->prev = tail;
tail = curr;
}
}

void cetak()
{
if(head==NULL)
{
printf("data kosong");
}
else
{
curr = head;
while(curr)
{
printf("%d ", curr->angka);
curr=curr->next;
}
}
}

void pop_depan()
{
if(head==NULL)
{
printf("tidak ada data");
getchar();
}
else if(head==tail)
{
curr=head;
free(curr);
head = tail = curr = NULL;
}
else
{
curr=head;
head=head->next;
free(curr);
head->prev = NULL;
}
}

void pop_belakang()
{
if(head==NULL)
{
printf("tidak ada data");
getchar();
}
else if(head==tail)
{
curr=head;
free(curr);
head = tail = curr = NULL;
}
else
{
curr=tail;
tail=tail->prev;
free(curr);
tail->next = NULL;
}
}

void main()
{
int angka, pilih, pilih2, pilih3;

do
{
clear();
printf("1. Input\n");
printf("2. View\n");
printf("3. Delete\n");
printf("4. Exit\n");
printf("Pilih : ");
scanf("%d", &pilih); fflush(stdin);

switch(pilih)
{
case 1 :
{
clear();
do
{
printf("1. Push Depan\n");
printf("2. Push Belakang\n");
printf("Pilih : ");
scanf("%d", &pilih2); fflush(stdin);
}while(pilih2!=1 && pilih2!=2);

if(pilih2==1)
{
printf("Masukan Angka : ");
scanf("%d", &angka); fflush(stdin);
push_depan(angka);
}
else if(pilih2==2)
{
printf("Masukan Angka : ");
scanf("%d", &angka); fflush(stdin);
push_belakang(angka);
}
break;
}
case 2 :
{
clear();
cetak();
getchar();
break;
}
case 3 :
{
clear();
do
{
printf("1. Pop Depan\n");
printf("2. Pop Belakang\n");
printf("Pilih : ");
scanf("%d", &pilih3); fflush(stdin);
}while(pilih3!=1 && pilih3!=2);

if(pilih3==1)
{
pop_depan();
}
else if(pilih3==2)
{
pop_belakang();
}
break;
}
}
}while(pilih!=4);
}

0 komentar: