Friday, April 17, 2009

SINGLE LINKED LIST

#include
#include
#include
#include
struct node
{
int data;
struct node *ptr;
};
typedef struct node NODE;
NODE *head=NULL;
NODE *nn,*temp,*temp1,*temp2;
main()
{
int ch,r=1;
clrscr();
while(r)
{
printf("enter the choice\n");
printf("1.entering from the front\n");
printf("2.entering from the end\n");
printf("3.entering from the middle\n");
printf("4.deleting from the front\n");
printf("5.deleting from the end\n");
printf("6.display\n");
printf("7.deleting from the middle\n");
printf("8.exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:enterf();
break;
case 2: entere();
break;
case 3:enterm();
break;
case 4:delf();
break;
case 5:dele();
break;
case 6:display();
break;
case 7:delm();
break;
case 8:return;
}
printf("do you want to continue press 1 for yes and 0 for no\n");
scanf("%d",&r);
}
}
enterf()
{
int item;
nn=(NODE*)malloc(sizeof(NODE));
printf("enter the item to be inserted\n");
scanf("%d",&item);
if(head==NULL)
{
nn->data=item;
nn->ptr=NULL;
head=nn;
}
else
{
nn->data=item;
nn->ptr=head;
head=nn;
}
}

display()
{
if(head==NULL)
printf("empty list\n");
else
{
printf("elements in the list are\n");
temp=head;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->ptr;
}
}
}

entere()
{
int item;
nn=(NODE*)malloc(sizeof(NODE));
printf("enter the item to be inserted\n");
scanf("%d",&item);
if(head==NULL)
{
nn->data=item;
nn->ptr=NULL;
head=nn;
}
else
{
temp=head;
while(temp->ptr!=NULL)
{
temp=temp->ptr;
}
nn->data=item;
temp->ptr=nn;
nn->ptr=NULL;
}
}
delf()
{
if(head==NULL)
printf("empty list\n");
else if(head->ptr==NULL)
{
printf("deleted element =%d",head->data);
free(head);
head=NULL;
}
else
{
temp=head;
head=head->ptr;
printf("deleted element=%d",temp->data);
free(temp);
}
}
dele()
{
if(head==NULL)
printf("empty list\n");
else if(head->ptr==NULL)
{
printf("deleted element=%d",head->data);
free(head);
head=NULL;
}
else
{
temp1=head;
temp2=NULL;
while(temp1->ptr!=NULL)
{
temp2=temp1;
temp1=temp1->ptr;
}
printf("deleted element=%d",temp1->data);
free(temp1);
temp2->ptr=NULL;
}
}


enterm()
{
int pos,item,i;
if(head==NULL)
{
nn=(NODE*)malloc(sizeof(NODE));
printf("enter the item to be inserted\n");
scanf("%d",&item);
nn->data=item;
nn->ptr=NULL;
head=nn;
}
else
{
printf("enter the position where you want to insert the element\n");
scanf("%d",&pos);
temp1=head;
temp2=NULL;
for(i=1;i {
temp2=temp1;
temp1=temp1->ptr;
}
printf("enter the item to be inserted\n");
scanf("%d",&item);
nn=(NODE*)malloc(sizeof(NODE));
nn->data=item;
temp2->ptr=nn;
nn->ptr=temp1;
}
}

delm()
{
int pos,i;
if(head==NULL)
{
printf("empty list\n");
}
else if(head->ptr==NULL)
{
printf("deleted element=%d",head->data);
free(head);
head=NULL;
}
else
{
printf("enter the position of the element to be deleted\n");
scanf("%d",&pos);
temp1=NULL;
temp2=head;
for(i=1;i {
temp1=temp2;
temp2=temp2->ptr;
}
printf("deleted element=%d\n",temp2->data);
temp1->ptr=temp2->ptr;
}
}

No comments: