Now we will see how to delete node at first position in circular doubly link list.
Algorithm to delete first node in circular doubly link list:
In this algorithm, START is pointer to the first node of doubly list. The steps are below:- Declare TEMP = START
- If list has no node i.e. [START == NULL]
- Deletion not possible as no node in the list
- Else If list have only one node i.e. START->NEXT = START
- Set START = NULL
- Else
- Set START->NEXT->PREV = START->PREV
- Set START->PREV->NEXT = START->NEXT
- Set START = START->NEXT
- Free(TEMP)
- End If;
Function to delete node at first position in circular doubly link list:
int deleteAtFirst(NODE **start){
NODE *temp = *start;
int info = -1;
if(*start == NULL){
printf("\nError: No nodes\n");
}
else{
if((*start)->next == *start){
*start = NULL;
}
else{
(*start)->next->prev = (*start)->prev;
(*start)->prev->next = (*start)->next;
*start = (*start)->next;
}
info = temp->info;
free(temp);
}
return info;
}
Program to delete node at first position in the circular doubly link list:
#include <stdio.h>
#include <malloc.h>
#include
#include
typedef struct node{
struct node *prev;
int info;
struct node *next;
} NODE;
void insertAtFirst(NODE **, int);
int deleteAtFirst(NODE **);
void traverse(NODE **);
int main(){
NODE *start = NULL;
deleteAtFirst(&start);
insertAtFirst(&start, 3);
traverse(&start);
deleteAtFirst(&start);
insertAtFirst(&start, 24);
insertAtFirst(&start, 4);
traverse(&start);
deleteAtFirst(&start);
traverse(&start);
return 0;
}
void insertAtFirst(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
ptr->info = info;
if(*start == NULL){
*start = ptr;
ptr->next = ptr;
ptr->prev = ptr;
}
else{
ptr->next = *start;
ptr->prev = (*start)->prev;
(*start)->prev->next = ptr;
(*start)->prev = ptr;
*start = ptr;
}
}
int deleteAtFirst(NODE **start){
NODE *temp = *start;
int info = -1;
if(*start == NULL){
printf("\nError: No nodes\n");
}
else{
if((*start)->next == *start){
*start = NULL;
}
else{
(*start)->next->prev = (*start)->prev;
(*start)->prev->next = (*start)->next;
*start = (*start)->next;
}
info = temp->info;
free(temp);
}
return info;
}
void traverse(NODE **start){
NODE *ptr = *start;
if(ptr == NULL){
printf("\nEmpty list\n");
return;
}
while( ptr->next != *start ){
printf("%d ",ptr->info);
ptr = ptr->next;
}
printf("%d\n",ptr->info);
}
Output:Error: No nodes 3 4 24 24 Error: No nodes
Comments
Post a Comment