Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
Its better you should write the code instead of writing comments.
Let the code say it all
Exactly... I agree with pers3us. It's better you do ur homework by yourself rather than putting such questions under a big company's name.
It's not like it's impossible that Amazon would ask this question. They certainly ask harder questions, but they ask easy ones too.
Let me clarify few things here -
1. Big companies can ask simple questions.They have done it in the past and they are already doing it.
2. Questions posted here are just to give an idea about what is being asked these days and not about finding solution.
3. I was able to solve it and also knewing the solution...but I didn't wrote the solution because it was really too simple.
Straight forward answer is:
Keep checking whether the value in the next node is equal to the given value. If true you just assign the next pointer in the current node to the next pointer ie
if(ptr->next.value==number)
ptr->next=ptr->next->next
else
ptr=ptr->next
I think you are confused with the question ...the node no. is given and not its value ..like deleteNode(head,5) which means you have to delete 5th node.
for(int i=0; i < nodeNum-1; i++)
{
node = node->next;
}.
tempNode = node->next;
node->next = node->next->next;
free(tempNode);
One simple solution:
Copy the next node of given node no. to given node. So given node value is overwritten and delete next node.
Lets say:
1-2-3-4-5-6-7-8
you want to delete 5 and your pointer points to 5.
So copy 6 in place of 5 and delete 6 as
5->next = 5->next->next.
But this won't work when you want to delete last node and your pointer points to last node.
Yes it might be easy, but this is a question to see how carefully you deal with all cases and code that up.
For instance, what happens if we delete the head? The last node? What if the node pointer is not found in the list?
C code. I am pretty sure there are bugs.
// Delete node from singly linked list starting at head.
// returns head of linked list with node deleted.
List * deleteNode (List *head, List *node) {
if (!head || !node) return head;
List dummy;
dummy->next = head;
List * cur = head;
List *prev = &dummy;
while (cur != node && cur != NULL) {
prev = cur;
cur = cur->next;
}
// at this point, either cur is NULL or node.
if (cur == node) {
prev->next = node->next;
}
return dummy.next;
}
Its better if you did your homework by yourself. :)
- pers3us March 20, 2012