Hello Friends,
Today we discuss about Circular Singly Linked List Deletion
Function for Delete Node From Beginning or Delete First Node:
void delete_beg()
{
struct node *f=head;
while(f->next!=head)
{f=f->next;}
head=head->next;
f->next=head;
}
Function for Delete Node From Specific Position or Delete in between:
void delete_spec()
{
struct node *p=head;
int i,pos;
printf("\nEnter Position where you want to add node:");
scanf("%d",&pos);
for(i=1; i<pos-1; i++)
{p=p->next;}
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
newnode->next=p->next;
p->next=newnode;
}
Function for delete last Node:
void delete_spec()
{
struct node *p=head,*q=head;
int i,pos,j;
printf("\nEnter Position which you want to delete:");
scanf("%d",&pos);
for(i=1; i<pos-1; i++)
{p=p->next;}
for(j=1; j<pos; j++)
{
q=q->next;
}
p->next=q->next;
free(q);
}
Full Program For Deletion:
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *newnode,*head,*temp;
void create()
{
int i,num;
printf("\nEnter How many nodes you want to create:");
scanf("%d",&num);
for(i=1; i<=num; i++){
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&newnode->data);
if(head==NULL)
{
head=temp=newnode;
newnode->next=head;
}else{
newnode->next=head;
temp->next=newnode;
temp=temp->next;
}}}
void display()
{
struct node *disp=head;
while(disp->next!=head)
{
printf("%d",disp->data);
disp=disp->next;
}
printf("%d",disp->data);
}
void delete_beg()
{
struct node *f=head;
while(f->next!=head)
{f=f->next;}
head=head->next;
f->next=head;
}
void delete_spec()
{
struct node *p=head,*q=head;
int i,pos,j;
printf("\nEnter Position which you want to delete:");
scanf("%d",&pos);
for(i=1; i<pos-1; i++)
{p=p->next;}
for(j=1; j<pos; j++)
{
q=q->next;
}
p->next=q->next;
free(q);
}
void delete_last()
{
struct node *last=head,*a;
while(last->next!=head)
{
a=last;
last=last->next;
}
a->next=head;
free(last);
last=NULL;
}
void main()
{
while(1)
{
int choice;
printf("\n1.Create,\n2.display,\n3.Delete First Node, \n4.Delete specific position,\n5.Delete Last Node,\n6.Exit");
printf("\nEnter Your Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
delete_beg();
break;
case 4:
delete_spec();
break;
case 5:
delete_last();
break;
case 6:
exit(0);
break;
default:
printf("\nEnter Correct Option:");
break;
}
}
getch();
}
For Run Program with out any error use full program.
No comments:
Post a Comment