Sunday, July 7, 2013

Insert into Doubly Linked List

Here is a small snippet including the insertBefore function of a DLL.
void DoublyLinkedList::insertBefore(int d)
{
  DLLNode* newnode = new DLLNode();
  newnode->data = d;

  if(cur == front)
  {
    front = newnode;
  }

  if(cur)
  {
    newnode->next = cur;

    if(cur->prev)
    {
      newnode->prev = cur->prev;
      cur->prev->next = newnode;
    }

    cur->prev = newnode;
  }
  else
  {
    front = cur = back = newnode;
  }

  size++;
}
I found it easier to visualize the list by drawing the nodes on paper.

No comments:

Post a Comment