Interview Questions

Write a function that would: return the 5th element from the end in a singly. .....

Software QA/Tests Interview Questions from Microsoft


(Continued from previous question...)

Write a function that would: return the 5th element from the end in a singly. .....

Question:
Write a function that would: return the 5th element from the end in a singly linked list of integers, in one pass, and then provide a set of test cases against that function


maybe an answer:


Use two pointers with the distance of 5 elements. Once the first pointer hit the end then we can either get the 5th elements or null if the list has less than 5 elements.

Node* NthLastElementList(Node* list, int n)
{
Node* p = list;
while (p && n != 0)
{
p = p->next;
n--;
}
if (n != 0)
{
return NULL;
}
else
{
while (p)
{
p = p->next;
list = list->next;
}
return list;
}
}

Other Interview Questions