Amazon Interview Question
'n' = node to be inserted
'p' = node after which it has to be inserted
n-> next = p->next;
p-> next = n;
2nd Anonymous and pk: both of you guys send your answers along with the question to Amazon guys they'll be more than happy to hire you two knowing you have solved the problem them might be trying to solve since the inception of the company itself! rather publish a paper on it with the title something like " How to access any element of a linked list in const time, O(1) similar to an array".
:) was just kidding
i shd have put thin in quote "thats the only answer this question deserves."
I knew when i saw this Q first, it looks like either half explained Q or stupid Q. Per me this is not anywhere near qualify for a a brain teaser or datastructure Q.
BTW I will be more than happy to replace the inventor of this Q :P.
I normally don't say this but I hope all you smart guys above were joking and not serious... Especially the belivers of "middle" pointer theory...
Here's my take. Since interviewer only said "linked list" without specifying / constraining the type of list (doubly linked, singly linked....etc.), I choose to use a Circular linked list.
Add the item right at the head. I'd then argue my way into convincing him that its in the "middle" of the list.
I think it is not possible to do so in a single step i.e O(1). Had it been mentioned that insertion is allowed at the middle of the list then the last two proposals might have worked, but I'm afraid as we don't have such assumptions given in the question. BTW, the idea of circular list is good to fool around the interviewer as the Qs is kinda vague.
I guess this question is about to find middle point of linked list without traversal whole linked list. Solution: 2 pointer, the first one go 1 step each time, the other go 2 step each until the end, the first pointer position is middle.
use an additional pointer *mid and also maintain the length of the linklist while inserting to the linklist
for every insertion insert at the mid pointer and increment the length. if the new length is odd then increment mid=mid->next.
this way the mid will always point to the middle of the linklist.
It is not a single step but is not an iterative traversal, in a call k should be 1
public static int AddInMid(Elem node,int k) {
int count = 0;
if (node != null)
{
count = AddInMid(node.next, k+1)+1;
if (count==k+1||count==k) {
Elem el = node.next;
node.next = new Elem();
node.next.next = el;
}
}
return count;
}
Simple answer: Not Possible
- Anonymous September 02, 2009without traversing the nodes/one step.