You are on page 1of 4

#include <stdio.

h>
#include <stdlib.h>
#include <conio.h>
typedef struct simpul node;
struct simpul
{
int data;
node *next;
};
node *head=NULL,*tail=NULL, *baru, *before, *after, *hapus, *temp;
void alocate(int x)
{
baru=(node *)malloc(sizeof(node));
if(baru==NULL)
{
printf("\nalokasi gagal!\n");
}
else
{
baru->data=x;
baru->next=NULL;
}
}
void tampil()
{
node *p=head;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
void sisipawal()
{
baru->next=head;
head=baru;
}
void sisipakhir()
{
tail=head;
if(head==NULL)
sisipawal();
while(tail->next!=NULL)
{
tail=tail->next;
}
tail->next=baru;
}
void sipseb(int n)
{
before=head;
if(head==NULL || before->data==n)
sisipawal();
else
{
while(before->next!=NULL && before->next->data!=n)
{
before=before->next;
}
if(before->next==NULL)
printf("\nsimpul tidak ada\n");
else
{
baru->next=before->next;
before->next=baru;
}
}
}
void sipset(int n)
{
after=head;
if(head==NULL)
sisipawal();
else if(after->data==n)
sisipakhir();
else
{
while(after->next!=NULL && after->data!=n)
{
after=after->next;
}
if(after->data!=n)
printf("simpul tidak ada\n");
else
{
baru->next=after->next;
after->next=baru;
}
}
}
void free_node(node *p)
{
free(p);
p=NULL;
}
void hapusawal()
{
hapus=head;
head=head->next;
free_node(hapus);
}
void hapusakhir()
{
tail=head;
while(tail->next->next!=NULL)
{
tail=tail->next;
}
/*hapus=tail->next;
tail->next=NULL;
free_node(tail->next);//hapus);???????????*/
hapus=tail->next;
tail->next=NULL;
free_node(hapus);
}
void hapustengah(int n)
{
before=head;
after=head;
if(head==NULL)
printf("tidak ada yang di hapus!");
else if(after->data==n)
hapusawal();
else
{
while(after->next!=NULL && after->data!=n)
{
before=after;
after=after->next;
}
if(after->data!=n)
printf("yang di hapus tidak ada\n");
else
{
before->next=after->next;
hapus=after;
after=NULL;
free_node(hapus);
}
}
}
void main()
{
int pil,n,x;
char kar='y';
while(kar=='y')
{
printf("\n\n1. Sisip awal\n2. Sisip akhir\n3. Sisip sebelum simp
ul\n4. Sisip setelah simpul\n5.hapus awal\n6.hapus akhir\n7.hapus tengah\n8. Qui
t\npilihan: ");
scanf("%d",&pil);
switch (pil)
{
case 1:
printf("\nmasukkan angka: ");
scanf("%d",&n);
alocate(n);
sisipawal();
tampil();
break;
case 2:
printf("\nmasukkan angka: ");
scanf("%d",&n);
alocate(n);
sisipakhir();
tampil();
break;
case 3:
printf("\nmasukkan angka: ");
scanf("%d",&n);
printf("\nmasukkan simpul ke: ");
scanf("%d",&x);
alocate(n);
sipseb(x);
tampil();
break;
case 4:
printf("\nmasukkan angka: ");
scanf("%d",&n);
printf("\nmasukkan simpul ke: ");
scanf("%d",&x);
alocate(n);
sipset(x);
tampil();
break;
case 5:
hapusawal();
tampil();
break;
case 6:
hapusakhir();
tampil();
break;
case 7:
printf("\nmasukkan simpul ke: ");
scanf("%d",&x);
hapustengah(x);
tampil();
break;
case 8:
kar='n';
break;
default :
break;
}
}
}

You might also like