Selasa, 27 April 2010

Single Linked List

Penggunaan Push Depan, Push Belakang, Pop Depan, Pop Belakang


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

struct data
{
int angka;
struct data *next;
}*head=NULL, *curr=NULL, *tail=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 = NULL;

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

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

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

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

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

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

int 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", &pilih3); fflush(stdin);
}while(pilih3!=1 && pilih3!=2);

if(pilih3==1)
{
printf("Masukan angka : ");
scanf("%d", &angka); fflush(stdin);
push_depan(angka);
}
else if(pilih3==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", &pilih2); fflush(stdin);
}while(pilih2!=1 && pilih2!=2);

if(pilih2==1)
{
pop_depan();
}
else if(pilih2==2)
{
pop_belakang();
}
break;
}

}
}while(pilih!=4);
}


Onez Sumlang - 27 April 2010

0 komentar: