Add Node Before/After
In this lesson, you will learn how to add a node before or after a specified node.
We'll cover the following...
In this lesson, we consider how to add nodes either before or after a specified node in a doubly-linked list. Once we cover the concept of how to perform this action, we follow through with a Python implementation.
The general approach to solve this problem would be to traverse the doubly linked list and look for the key that we have to insert the new node after or before. Once we get to the node whose value matches the input key, we update the pointers to make room for the new node and insert the new node according to the position specified.
Add Node After
We’ll break up this scenario into two cases:
- The node that we have to insert after the new node is the last node in the doubly linked list so that the next of that node is NULL.
In the above case, we’ll make a call to the append
method that we implemented in the last lesson. append
will handle everything for us and perfectly works in this scenario as we have to insert the new node after the last node, which is what append
method does.
- The node that we have to insert after the new node is not the last node in the doubly linked list.
Let’s look at the illustration below to check how we will handle the second case:
Hope the slides above ...