Hey so I am creating a doubly linked list generic class but I'm having trouble wrapping my head around a piece of code, mainly the code to add an item to the beginning of my list.
my node structure is protected within my class and looks like..
1 2 3 4 5 6 7
|
struct Node{
genClass info; // generic type
Node *next, *prev;
Node(genClass el, ElNode *n = 0, ElNode *p = 0)
{ info = el; next = n; prev =p; }
} *head, *tail, *tmp;
genClass el;
|
The code that I am having trouble understanding is the following :
1 2 3 4 5 6 7 8 9
|
template<class genClass>
void DoublylinkedList<genClass>::AddToHead(const genClass & el)
{
if(head) {
head = new Node(el,head,0);
head->next->prev = head;
} else
head=tail=new Node(el);
}
|
The way I'm currently reading the function is as follows...
1) If the head node contains data(we do not have an empty list)
2) Point the current head node to a new node containing the element passed to AddToHead as the info - but this is where I get confused...
Is the second parameter in the statement
head = new Node(el,head,0)
assigning the current node as the next node in the list ? How is this possible? Is the head not actually pointing to the new Node until after this statement?
Also the second line of the if block confuses me - I don't understand what's happening.
I think I understand the else statement, it's just saying that we only have one item in the list so the head and tail point to the same node.