Skip to content
Home » Deleting a node at the random position in a circular doubly linked list

Deleting a node at the random position in a circular doubly linked list

Below is the code to delete a node at the random position in a circular doubly linked list

#include <stdio.h>
#include <stdlib.h>
struct node{
struct node *prev;
int data;
struct node *next;
};
struct node *add_to_empty(int data){
struct node *temp=malloc(sizeof(struct node));
temp->prev=temp;
temp->data=data;
temp->next=temp;
return temp;
}
struct node *ad_end(struct node *tail,int ele){
struct node *newp=add_to_empty(ele);
if(tail==NULL){
return newp;
}else{
struct node *temp=tail->next;
newp->prev=tail;
newp->next=temp;
tail->next=newp;
temp->prev=newp;
tail=newp;
return tail;
}
}
struct node *del_rand(struct node *tail,int pos){
struct node*temp=tail->next;
while(pos>1){
temp=temp->next;
pos--;
}struct node *temp2=temp->prev;
temp2->next=temp->next;
temp->next->prev=temp2;
free(temp);
if(temp==tail){
tail=temp2;
}
return tail;
}
void print(struct node *tail){
if (tail == NULL) {
printf("Linked list is empty.\n");
return;
}

struct node *temp = tail->next;
do {
printf("%d ", temp->data);
temp = temp->next;
} while(temp != tail->next);
}

int main(){
struct node *tail=NULL;
tail=add_to_empty(20);
tail=ad_end(tail,60);
tail=ad_end(tail,30);
tail=ad_end(tail,50);
tail=del_rand(tail,2);
print(tail);
}

20 30 50