Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
how to understand "one of the reason to add head node to the link list is that the operations on the empty list and the non-empty list can be the same."
It will be much better if there is a sample showing the details. Thank you!
Posted
Comments
Sergey Chepurin 29-Jul-11 14:09pm    
If you simply search for, say, "dummy head node in linked list", you will get a lot of good and reliable answers on this including pages from universities.

Adding a dummy head node makes the list more homogeneous in that every node is pointed to by another node. Without it, the first node is different, it is pointed to by the head pointer, not by a node.

In the case of an insertion operation, you insert after a given node. When the list is empty, there is no such node and you have to handle this as a special case. When there is a dummy node, you can always insert after it.
 
Share this answer
 
v2
The STL std::list is implemented as a dual linked-list with a dummy node working as both head and tail.

Just look the <list> header.
 
Share this answer
 
Me think adding a non-functional (dummy) node to a linked-list is not a good thing.

Just check the initial pointer against NULL.

for example (simplified-ish code)

struct node
{
  int data;
  node* next;
};

node* myList = NULL; // empty list.

// traversal on an empty list; if the list is empty it will not traverse.
node* myIterator = myList;
while ( myIterator != NULL )
{
   myIterator = myIterator->next;
};
 
Share this answer
 
Comments
Philippe Mori 29-Jul-11 19:38pm    
There is a big problem with that solution... How to you pass an empty list to a function that could add items to the list?
Maximilien 30-Jul-11 10:39am    
The same way you pass a pointer to a function that will modify it : by passing a pointer to the pointer or a reference to the pointer.

void f( node** list );
void f( node*& list );
// or is it ? (I don't remember).
void f(node &* list );

M.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900