Above question was asked to me in my interview.
Though I am still waiting for the result, I am wondering if my approach is correct or if there is any better solution?
struct Node
{
int data;
Node * next;
};
Node *function( struct Node *head)
{
if ( ! head)
{
std::cout <<" no linked present";
return 0;
}
Node *current, *temp;
temp = NULL;
current = head;
int counter = 0;
while( current != NULL)
{
counter ++;
current = current->next;
if( counter >= 5)
{
if( temp == NULL)
temp = head;
else
temp = temp->next;
}
}
return (temp);
}
IF you guys have better optimal solution , please post it here.
Thanks to everyone
Sam
For the single-linked list your solution should be optimal. For the double-linked list, you could go from the back.