Now we will see how to insert a new node at the last position of doubly link list.
Algorithm for insertion at last position in circular doubly link list:
In this algorithm, START is pointer to first node of list and PTR is the node to be inserted at last. The steps 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->PREV = PTR
- Set PTR->NEXT = PTR
- Else
- Set PTR->NEXT = START
- Set PTR->PREV = START->PREV
- Set START->PREV->NEXT = PTR
- Set START->PREV = PTR
- End If;
Function to insert node at last position in circular doubly link list:
void insertAtLast(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;
}
}
Program to insert at last 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 insertAtLast(NODE **, int);
void traverse(NODE **);
int main(){
NODE *start = NULL;
insertAtLast(&start, 3);
insertAtLast(&start, 24);
insertAtLast(&start, 4);
traverse(&start);
return 0;
}
void insertAtLast(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;
}
}
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);
}
3 24 4
Comments
Post a Comment