Sunday, November 16, 2008

How to Print a data from a binary tree In ascending order

Code snippet to Print a data from a binary tree – In-order(ascending)


// recursive version


Void PrintTree ( struct * node node )
{
if ( node == NULL )
return;

PrintTree(node - > left );
Printf(“%d”, node - > data);
PrintTree(node - > right );
}

Tips for reducing unexpected buffer errors

When using functions such as strncpy() that take a size input parameter, you should use the size of the destination buffer and not the source buffer for correct functionality!

Following code snippet is an example of incorrect usage -

strncpy(dest, src, sizeof(src));

//If sizeof(src) > sizeof(dest) this would give unexpected results;


Therefore, the correct and safe usage should be,

memset(dest, 0, sizeof(dest)); //Fill the buffer with null characters

strncpy(dest, src, sizeof(dest)-1);

//sizeof(dest)-1 takes care of the space for the terminating null character

Sunday, November 9, 2008

C++ function to return Nth the node from the end of the linked list in one pass.

C++ function to return Nth the node from the end of the linked list in one pass.

Node * GetNthNode ( Node* Head , int NthNode )
{
Node * pNthNode = NULL;
Node * pTempNode = NULL;
int nCurrentElement = 0;

for ( pTempNode = Head; pTempNode != NULL; pTempNode = pTempNode->pNext )
{
nCurrentElement++;
if ( nCurrentElement - NthNode == 0 )
{
pNthNode = Head;
}
else
if ( nCurrentElement - NthNode > 0)
{
pNthNode = pNthNode - > pNext;
}
}
if (pNthNode )
{
return pNthNode;
}
else
return NULL;
}