## C++ OOP: doubly linked list

To add an element to the doubly linked list, you need to consider 4 things:

1. When the list is empty, to add a new element to the list, you only let the pfirst and plast links point to the new item.

2.If the new element is to be added to the beginning of  the list, you will need to let the next link of the new item points to the pfirst, set its previous link to null, and then update the pfirst to point to the new item.

3. If the new element is to be added to the middle position of the list, you need to let a link move to the position that the new element will be placed in. Then exchange the links as shown below:

4. If the new element is to be added to the last of the list, you need to let the next link of the plast point to the new element, and the previous link of the new element point to the plast. Then update the plast to point the new element.

public void insert(T val, int pos)

{

ListNode<T> newnode = new ListNode<T>(val);

int inserted = 1;

//empty list

if (pfirst == null && plast == null)

{

newnode.prev = null;

newnode.next = null;

pfirst = newnode;

plast = newnode;

}

//Insert at the beginning of the list

else if (pos == 1)

{

newnode.next = pfirst;

newnode.prev = null;

pfirst = newnode;

}

//Insert in the middle of the list

else if (pos > 1 && pos <= countitem())

{

ListNode<T> ta;

ta = pfirst;

for (int t = 1; t < pos; t = t + 1) { ta = ta.next; } //move to the insertion point

newnode.next = ta;

newnode.prev = ta.prev;

ta.prev.next = newnode;

ta.prev = newnode;

}

else if (pos == countitem() + 1)

{

newnode.next = null;

plast.next = newnode;

newnode.prev = plast;

plast = newnode;

}

else { inserted = 0; Console.WriteLine("Invalid position!"); }

if (inserted != 0) Console.WriteLine("Inserted") ;

}

}