C Program For Deleting A Node In A Doubly Linked List
Last Updated :
25 Apr, 2023
Pre-requisite: Doubly Link List Set 1| Introduction and Insertion
Write a function to delete a given node in a doubly-linked list.
Original Doubly Linked List
Approach: The deletion of a node in a doubly-linked list can be divided into three main categories:
- After the deletion of the head node.
- After the deletion of the middle node.
- After the deletion of the last node.
All three mentioned cases can be handled in two steps if the pointer of the node to be deleted and the head pointer is known.
- If the node to be deleted is the head node then make the next node as head.
- If a node is deleted, connect the next and previous node of the deleted node.
Algorithm
- Let the node to be deleted be del.
- If node to be deleted is head node, then change the head pointer to next current head.
if headnode == del then
headnode = del.nextNode
- Set next of previous to del, if previous to del exists.
if del.nextNode != none
del.nextNode.previousNode = del.previousNode
- Set prev of next to del, if next to del exists.
if del.previousNode != none
del.previousNode.nextNode = del.next
C
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
struct Node* prev;
};
void deleteNode( struct Node** head_ref,
struct Node* del)
{
if (*head_ref == NULL || del == NULL)
return ;
if (*head_ref == del)
*head_ref = del->next;
if (del->next != NULL)
del->next->prev = del->prev;
if (del->prev != NULL)
del->prev->next = del->next;
free (del);
return ;
}
void push( struct Node** head_ref,
int new_data)
{
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
void printList( struct Node* node)
{
while (node != NULL)
{
printf ( "%d " , node->data);
node = node->next;
}
}
int main()
{
struct Node* head = NULL;
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
printf (
"Original Linked list " );
printList(head);
deleteNode(&head, head);
deleteNode(&head, head->next);
deleteNode(&head, head->next);
printf (
"Modified Linked list " );
printList(head);
getchar ();
}
|
Output:
Original Linked list 10 8 4 2
Modified Linked list 8
Complexity Analysis:
- Time Complexity: O(1).
Since traversal of the linked list is not required so the time complexity is constant.
- Space Complexity: O(1).
As no extra space is required, so the space complexity is constant.
Please refer complete article on Delete a node in a Doubly Linked List for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...