DEV Community

Cover image for Insert Before Double Linked List
Martin Corona
Martin Corona

Posted on • Updated on

Insert Before Double Linked List

In this Algorithm the way it works is by adding a node before the node is selected, Therefore, I'll explain the parts of this Algorithm:

{x is going to be the node to select, data is the information to add}

{Q, T and R are pointers}

{Info is the content of the node, linkft is the pointer to the left, linker is the pointer to the right}

Alt Text

First of all, We'll need a list done,then we select the node to add before, which in this case is 66 and the node we'll add is 24 as show in the Figure 1.
Alt Text
Figure 1 The list.

After that, We going to make that the node Q point to the head, as show in the Figure 2.
Alt Text
Figure 2 node Q point to the first node.

So, for to check through all of the list we going to use a loop, for look up the node we select and different to NULL, as show in the Figure 3 and Figure 3.1.
Alt Text
Figure 3.
Alt Text
Figure 3.1 This loop will check node by node, which we selected.

Once, the Algorithm found the node which we selected, then we create the new node,as show in the Figure 4.

Alt Text
Figure 4 Create new node 24 which is the pointer T.

So, we start by doing that the node T point to the right side of the node Q, as show in the Figure 5.

Alt Text

Figure 5 node T point to node Q.

After that, The node R will point to the left node of the node Q, as show in the Figure 6.

Alt Text
Figure 6 node R point to the left side of the node Q.

In the next line, the node Q will point to the left side of the node T,as show in the Figure 7.
Alt Text
Figure 7 node Q point to the left side of the node T.

In the next Figure 8, the Algorithm check if the node Q is the head of the List, if the case is true, then the head will point to node T and T link left will going to be NULL, but as we see in this case, node Q is not at the beginning, pass to the next case.

Alt Text
Figure 8 Check if node Q is the beginning of the list.

Therefore, the node R will point to the right side of the node T, as show in the Figure 9.
Alt Text
Figure 9 node R point to the right side of node T.

As last step, the node T will point to the left side of R, as show in the Figure 10.
Alt Text
Figure 10 node T point to the left side of node R.

Finally,

the node T have been added to the list, as show in the Figure 11.
Alt Text
Figure 11 node T added to the list.

Alt Text

Top comments (0)