Thursday, October 16, 2008

Interview Questions

How to find the middle node from a link list?

middle = last = head;

while( last!=NULL && last->next != NULL )
{
middle = middle->next;
last = last->next->next;
}

// here middle element is in the middle of list


How to count the number of on bits in the number?

count=0;
while( n>0 )
{
if( n & 1 )
{
count++;
}
n = n>>1;
}


How can you delete a node from a singly link list?
you are provided with only the pointer to node.


Save next node.
Copy all the data from the next node to the current node.
copy the next pointer from next node to the current node.
then delete the next node.

temp = node->next;
node->data = node->next->data;
node->next = node->next->next;
delte temp;

This would not work if the provided node is last element.

Monday, August 4, 2008

How to create non-blocking socket?

Alternative to blocking socket we can have non-blocking socket. Any call on these socket will return without blocking.
Following code illustrates how to create a non-blocking socket.

SOCKET s;
unsigned long ulMode = 1;
int nRet;

s = socket(AF_INET, SOCK_STREAM, 0);
nRet = ioctlsocket(s, FIOBIO, (unsigned long *) &ulMode);
if (nRet == SOCKET_ERROR)
{
//Failed to put the socket into nonblocking mode
}

Here ulMode value 1 enables socket non-blocking mode.
changing this value to 0 disables non-blocking mode.

The WSAAsyncSelect and WSAEventSelect functions automatically set a socket to nonblocking mode. If WSAAsyncSelect or WSAEventSelect has been issued on a socket, then any attempt to use ioctlsocket to set the socket back to blocking mode will fail with WSAEINVAL.

To set the socket back to blocking mode, an application must first disable WSAAsyncSelect by calling WSAAsyncSelect with the lEvent parameter equal to zero, or disable WSAEventSelect by calling WSAEventSelect with the lNetworkEvents parameter equal to zero.