Yahoo Interview Question
Software Engineer / DevelopersThe solution does not fail. The first pointer always points to the last element of the first list.
Check it with 4 or 6. They both work. With even 2 elements.
In case of two we need to switch the first and second lists because when there are 2 elements, when the loop ends pointer 1 points to 2 second and pointer 2 points to the first element.
Take 2 pointers, move one pointer 2 nodes and other 1 node
In case of 4 nodes
Pointer 1 => pointing to 2 node
Pointer 2 => pointing to 4th node
In case of 5 nodes
Pointer 1 => pointing to 3rd node
Pointer 2 => pointing to NULL.
Point pointer 2 to pointer 1->next
Use two pointers to traverse the link list, the first one move 1 step, second one move 2 steps, when the second pointer reach the end, set the head of the second list to be the next of the first pointer (and also remove the link from the previous pointer)
- Nat September 12, 2010public node* SplitList(node* head)
{
if(head == null)
{
return;
}
node* p1 = head;
node* p2 = head;
while(p2 != null)
{
p2 = p2->next;
if(p2!=null)
{
p2 = p2->next;
}
p1 = p1->next;
}
node* head2 = p1->next;
p1->next = null;
return head2;
}