Linked list
//linked list
#include<stdio.h>
struct node
{
int data;
struct node *link;
};
struct node *root;
void main()
{
int a,x;
while(1)
{
printf("\n1:add\n");
printf("2:display\n");
printf("3:delete\n");
printf("4:length\n");
printf("5:exit\n");
scanf("%d",&a);
switch(a)
{
case 1:add();
break;
case 2: display();
break;
case 3: delete();
break;
case 4: x=length();
printf("length=%d\n",x);
break;
case 5: exit(1);
default : printf("Invalid Input\n");
}}
}
void add()
{ int b;
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("enter data \n");
scanf("%d",&temp->data);
temp->link=NULL;
printf("where you want to enter the data ?\n");
printf("1:at first position\n");
printf("2:at last position\n");
printf("3:at specific position\n");
scanf("%d",&b);
if(b==1)
{
first:
if(root==NULL)
{
root =temp;
}
else
{
temp->link=root;
root =temp;
}
}
else if(b==2)
{ last:
if(root==NULL)
{
root =temp;
}
else
{
struct node *p;
p=root;
while(p->link!=NULL)
{
p=p->link;
}
p->link=temp;
}
}
else if(b==3)
{ int loc,i=1;
struct node *q;
q=root;
printf("enter the location where you want to enter the data \n");
scanf("%d",&loc);
if(loc==1)
{
goto first;
}
else if(length()+1==loc)
goto last;
else if(length()<loc)
printf("can't place any data in %d location becouse other positions are empty before this location",loc);
else
{
while(i<loc-1)
{
q= q->link;
i++;
}
temp->link=q->link;
q->link =temp;
}
}
}
void display()
{
int i=1;
struct node *temp;
temp=root;
if(root==NULL)
printf("empty\n");
else
{
while(i<=length())
{
printf("element %d =%d\n",i,temp->data);
temp=temp->link;
i++;
}
}
}
void delete()
{ if(root==NULL)
printf("empty\n");
else
{
int loc,i=1;
struct node *r;
struct node *s;
r=root;
s=root->link;
printf("enter the location\n");
scanf("%d",&loc);
if(loc==1)
{
r=root;
root=root->link;
free(r);
}
else
{
while(i<loc-1)
{ r=r->link;
s=s->link;
i++;
}
r->link=s->link;
s->link=NULL;
free(s);
}
}
}
int length()
{
if(root==NULL)
{
return 0;
}
else
{
struct node *temp;
temp=root;
int i=0;
while(temp!=NULL)
{
temp=temp->link;
i++;
}
return i;
}
}
Comments
Post a Comment