I am writing a method that does insertion into a doubly linked list and I was looking for some assistance with my code to see if I was heading in the write direction and what needs to be fixed to make this work.

Instructions
template <class T>
Iterator<T> List<T>::insert(Iterator<T> pos, const T& newItem)

This method takes two arguments, an Iterator object that points to a list node, and an item to be inserted. The method should create a new list node that contains the item to be inserted and insert it into the list before the node pointed to by the Iterator pos. The method should return an Iterator that points to the newly inserted node.

template <class T>
      Iterator<T> List<T>::insert(Iterator<T> pos, const T& newItem)
      {
      LNode<T>* nodePtr;
      nodePtr = new LNode<T>(newItem);

      if(pos == head)
        {
        nodePtr->prev = NULL;
        nodePtr->next = head;
        head->prev = nodePtr;
        head = nodePtr;
        }
      if(pos != head && pos != tail)
        pos->prev = nodePtr;
      if(pos == tail)
        {
        nodePtr->next = NULL;
        nodePtr->prev = tail;
        tail->next = nodePtr;
        tail = nodePtr;
        }
      return Iterator<T>(nodePtr);
      }

After an insertion in a middle of the list you lose a pointer of pos->next
To fix that you must place new pointer there
Something like this

if(pos != head && pos != tail)
{
        pos->prev = nodePtr;
        nodePtr->prev = pos->prev->prev; //sets a previous node of new node
        nodePtr->next = pos; //sets a next node of new node
}

I hope it'll help you.

This article has been dead for over six months. Start a new discussion instead.