To delete the last node of a doubly linked list in C, you can follow these steps:
1. Check if the list is empty. If it is empty, there is nothing to delete.
2. If the list is not empty, check if there is only one node in the list. If there is only one node, set the head and tail pointers to NULL and free the node.
3. If there is more than one node in the list, traverse the list from the head to the tail and find the last node.
4. Set the tail pointer to the previous node of the last node.
5. Set the next pointer of the previous node of the last node to NULL.
6. Free the memory occupied by the last node.
Here's the code implementation:
```
// Node structure
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// Function to delete last node
void deleteLastNode(struct Node** head_ref, struct Node** tail_ref) {
// Check if list is empty
if (*head_ref == NULL) {
printf("List is empty\n");
return;
}
// If there is only one node in the list
if ((*head_ref)->next == NULL) {
free(*head_ref);
*head_ref = NULL;
*tail_ref = NULL;
return;
}
// Traverse the list from head to tail
struct Node* current = *head_ref;
while (current->next != NULL) {
current = current->next;
}
// Set tail pointer to the previous node of last node
*tail_ref = current->prev;
// Set the next pointer of previous node of last node to NULL
current->prev->next = NULL;
// Free the memory occupied by the last node
free(current);
}
```
You can call the `deleteLastNode()` function with the head and tail pointers of the doubly linked list to delete the last node.
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