NVIDIA Interview Question
Software Engineer / Developersvoid swapNodes(Node **head) {
if(!*head)
return;
int first = 1;
Node *newHead;
while((*head)->next) {
Node *tmp = *head;
Data data = (*head)->data;
displayData(data);
Node *next = (*head)->next;
Node *after = NULL;
if(next->next)
after = next->next;
(*head)->data = next->data;
(*head) = next;
next->data = data;
next = tmp;
next->next = (*head);
if(first) {
newHead = next;
first = 0;
}
(*head)->next = after;
if(after)
(*head) = after;
}
*head = newHead;
}
lnode *swap_two(lnode *start)
{
lnode *ret;
lnode *next_two;
// Terminate Recursion
if (start == NULL || start->next == NULL)
return (start);
next_two = start->next->next;
ret = start->next;
start->next->next = start;
start->next = swap_two(next_two);
return (ret);
}
Functions return linked list in such order.
I used 3 pointers. Not sure if you can do it with two. If anyone has any suggestions please let me know! handles even # of nodes, odd # of nodes, 0, 1, 2 nodes.
}
- woohoo February 26, 2011