Write
C program to Insert & Delete nodes at Beginning, Middle and at End using
functions in Circular Linked List
#include
<stdio.h>
struct node
{
int data;
struct
node*link;
};
struct node *
getnode()
{
struct node
*p;
p=(struct
node *)malloc(sizeof(struct node));
printf("enter data into the node:");
scanf("%d",&p->data);
p->link=NULL;
return p;
}
int countnodes(struct node *f)
{
struct node
*temp;
int ct=0;
temp=f;
while(temp->link!=f)
{
ct++;
temp=temp->link;
}
ct++;
return ct;
}
struct node *
createnodes()
{
struct node
*first,*t,*temp;
char
ch='Y';
int ct=0;
while(ch=='Y')
{
if(ct==0)
{
first=getnode();
ct++;
temp=first;
first->link=first;
}
else
{
temp=first;
while(temp->link!=first)
{
temp=temp->link;
}
t=getnode();
temp->link=t;
t->link=first;
}
printf("do you want to continue:");
fflush(stdin);
ch=getchar();
}
return
first;
}
void
displaylist (struct node *f)
{
struct
node *temp;
temp=f;
while(temp->link!=f)
{
printf("%d-->",temp->data);
temp=temp->link;
}
printf("%d-->\n",temp->data);
}
/* struct node * insertnodes(struct node *f,int
pos)
{
struct
node *t,*t1,*n;
int ct,i;
ct=countnodes(f);
if(pos==1)
{
t=getnode();
t->link=f;
t1=f;
while(t1->link!=f)
{
t1=t1->link;
}
t1->link=t;
f=t;
}
else
if(pos>ct)
{
t=f;
for(i=1;i<ct;i++)
{
t=t->link;
}
n=getnode();
t->link=n;
n->link=f;
}
else
{
t=f;
t1=f;
for(i=1;i<pos;i++)
{
t=t->link;
}
for(i=1;i<pos-1;i++)
{
t1=t1->link;
}
n=getnode();
n->link=t;
t1->link=n;
}
return f;
} */
struct node
* deletefirstnode(struct node *f)
{
struct
node *temp,*t;
temp=f;
t=f;
while(temp->link!=f)
{
temp=temp->link;
}
f=f->link;
temp->link=f;
free(t);
return f;
}
struct node
*deletelastnode(struct node *f)
{
struct
node *temp,*t;
temp=f;
t=f;
while(temp->link!=f)
{
temp=temp->link;
}
while(t->link!=temp)
{
t=t->link;
}
t->link=temp;
free(temp);
return f;
}
struct node
*deletemiddlenode(struct node *f,int pos)
{
struct
node *temp,*t;
int i;
temp=f;
t=f;
for(i=1;i<pos;i++)
{
temp=temp->link;
}
for(i=1;i<pos-1;i++)
{
t=t->link;
}
t->link=temp->link;
free(temp);
return f;
}
void main()
{
int ct,n;
struct
node *first;
clrscr();
first=createnodes();
displaylist(first);
ct=countnodes(first);
printf("number of nodes=%d\n",ct);
/*
printf("Enter the node position to be inserted\n");
scanf("%d",&n);
first=insertnodes(first,n);
displaylist(first);*/
first=deletefirstnode(first);
displaylist(first);
first=deletelastnode(first);
displaylist(first);
getch();
}
No comments:
Post a Comment