Sentinel Node - Example

Example

Below shows an initialization of a sentinel node in a binary tree implemented in C programming language:

struct jsw_node { int data; int level; struct jsw_node *link; // link to next_left node; link to next_right node }; struct jsw_node *nil; // pointer to the sentinel node int jsw_init ( void ) { nil = (jsw_node*) malloc ( sizeof *nil ); // allocating memory for the sentinel node if ( nil == NULL ) // check for malloc failure return 0; // malloc failed to allocate memory nil->level = 0; nil->link = nil->link = nil; // link both right and left nodes to self (empty tree) return 1; // successful initialization }

As nodes that would normally link to NULL now link to "nil" (including nil itself), it removes the need for an expensive branch operation to check for NULL. NULL itself is known as a sentinel value, a different approach to the same problem.

Read more about this topic:  Sentinel Node

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)