To delete the first node of a doubly linked list using C, you can follow these steps:
1. Check if the list is empty. If it is, there is nothing to delete, so return from the function.
```
if (*headRef == NULL) {
printf("List is empty.\n");
return;
}
```
Here, `headRef` is a pointer to the pointer to the first node of the list.
2. If the list is not empty, store the address of the first node in a temporary variable and update the head pointer to point to the second node.
```
struct Node* temp = *headRef;
*headRef = temp->next;
```
3. If the second node exists, update its previous pointer to `NULL` because it is now the first node.
```
if (*headRef != NULL) {
(*headRef)->prev = NULL;
}
```
4. Free the memory occupied by the first node using the `free()` function.
```
free(temp);
```
The complete code for deleting the first node of a doubly linked list using C is shown below:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
void deleteFirstNode(struct Node** headRef) {
if (*headRef == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = *headRef;
*headRef = temp->next;
if (*headRef != NULL) {
(*headRef)->prev = NULL;
}
free(temp);
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
struct Node* node1 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node3 = (struct Node*)malloc(sizeof(struct Node));
node1->data = 1;
node1->prev = NULL;
node1->next = node2;
node2->data = 2;
node2->prev = node1;
node2->next = node3;
node3->data = 3;
node3->prev = node2;
node3->next = NULL;
head = node1;
deleteFirstNode(&head);
printList(head); // Output should be: 2 3
return 0;
}
```
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc