# Delete a node in a Doubly Linked List

Write a function to delete a given node in a doubly-linked list

Example:

Input: DLL = 2->45->3->1, Node = 45
Output:  2->3->1

Input: DLL = 2->45->3->1, Node = 1
Output:  2->45->3

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.

1. If the node to be deleted is the head node then make the next node as head.
2. 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.
• Set prev of next to del, if next to del exists.
if del.nextNode != none
del.nextNode.previousNode = del.previousNode
• Set next of previous to del, if previous to del exists.
if del.previousNode != none
del.previousNode.nextNode = del.next

Below is the implementation of the above approach:

## Javascript



Output

Original Linked list 10 8 4 2

Complexity Analysis:

• Time Complexity: O(1).
Since traversal of the linked list is not required so the time complexity is constant.
• Auxiliary Space: O(1).
As no extra space is required, so the space complexity is constant.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next