Now we will see how to delete node at first position in doubly link list.
Algorithm to delete first node in 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 have only one node i.e. START->NEXT = START
- Set START = NULL
- Else
- Set START = START->NEXT
- Set START->PREV = NULL
- Free(TEMP)
- End If;
Function to delete node at first position in doubly link list:
int deleteAtFirst(NODE **start){
NODE *temp = *start;
int info = -1;
if(*start == NULL){
printf("\nError: No nodes");
}
else if((*start)->next == NULL){
info = (temp)->info;
free(temp);
*start = NULL;
}
else{
info = (temp)->info;
*start = (*start)->next;
(*start)->prev = NULL;
free(temp);
}
return info;
}
Program to delete node at first position in the doubly link list:
#include <stdio.h>
#include <malloc.h>
typedef struct node{
int info;
struct node *next, *prev;
} NODE;
void insertAtLast(NODE **, int);
int deleteAtFirst(NODE **);
void traverse(NODE **);
int main(){
NODE *start = NULL;
insertAtLast(&start, 1);
insertAtLast(&start, 2);
traverse(&start);
deleteAtFirst(&start);
traverse(&start);
deleteAtFirst(&start);
traverse(&start);
deleteAtFirst(&start);
traverse(&start);
return 0;
}
int deleteAtFirst(NODE **start){
NODE *temp = *start;
int info = -1;
if(*start == NULL){
printf("\nError: No nodes");
}
else if((*start)->next == NULL){
info = (temp)->info;
free(temp);
*start = NULL;
}
else{
info = (temp)->info;
*start = (*start)->next;
(*start)->prev = NULL;
free(temp);
}
return info;
}
void insertAtLast(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
NODE *temp = *start;
ptr->info = info;
ptr->next = NULL;
if(*start == NULL){
*start = ptr;
ptr->prev = NULL;
}
else{
while(temp->next != NULL){
temp = temp->next;
}
ptr->prev = temp;
temp->next = ptr;
}
}
void traverse(NODE **start){
NODE *temp = *start;
while(temp != NULL){
printf("%d ", temp->info);
temp = temp->next;
}
printf("\n");
}
Output:1 2 2 Error: No nodes
Comments
Post a Comment