Now we will see how to insert a new node at first position in circular doubly link list.
Algorithm for insertion at first position in circular doubly link list:
In this algorithm, START is pointer to first node and PTR is node to be inserted. The step are as follows:- Create new node PTR
- Set the info field of PTR
- If list is empty i.e. START == NULL
- Set START = PTR
- Set PTR->NEXT = PTR
- Set PTR->PREV = PTR
- Else
- Set PTR->NEXT = START
- Set PTR->PREV = START->PREV
- Set START->PREV->NEXT = PTR
- Set START->PREV = PTR
- Set START = PTR
- End If;
Function to insert node at first position in circular doubly link list:
void insertAtFirst(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE)); //new node to insert
ptr->info = info; //set info field
if(*start == NULL){ //empty list
*start = ptr;
ptr->next = ptr;
ptr->prev = ptr;
}
else{
ptr->next = *start; //ptr's next points to first node
ptr->prev = (*start)->prev; // ptr's prev points to last node
(*start)->prev->next = ptr; //last node's next point to ptr
(*start)->prev = ptr; //first node's prev points to ptr
*start = ptr; //now ptr is first node
}
}
Program to insert at first position in the circular doubly link list:
#include <stdio.h>
#include <malloc.h>
typedef struct node{
struct node *prev;
int info;
struct node *next;
} NODE;
void insertAtFirst(NODE **, int);
void traverse(NODE **);
int main(){
NODE *start = NULL;
insertAtFirst(&start, 3);
insertAtFirst(&start, 24);
insertAtFirst(&start, 4);
traverse(&start);
return 0;
}
void insertAtFirst(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE)); //new node to insert
ptr->info = info; //set info field
if(*start == NULL){ //empty list
*start = ptr;
ptr->next = ptr;
ptr->prev = ptr;
}
else{
ptr->next = *start; //ptr's next points to first node
ptr->prev = (*start)->prev; // ptr's prev points to last node
(*start)->prev->next = ptr; //last node's next point to ptr
(*start)->prev = ptr; //first node's prev points to ptr
*start = ptr; //now ptr is first node
}
}
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);
}
4 24 3
Very easy explanation...
ReplyDeleteThank you...
Delete