Sunday, July 28, 2013

Binary Serialization of a Doubly Linked List

In order to properly store a list in a file, you must copy each node individually and avoid storing volatile memory addresses.

A binary read/write must accept a char* argument. Using a DLL consisting of integer data, we can simply cast the address of the integer and pass its size.
  int i = list.getValue();
  data.write((const char*)&i, sizeof(i));
The integer (4 bytes) will be written as 4 characters (1 byte each), which can be read back later on.

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.