Hi All,
I would like to know how it is possible to insert a node in a linked
list without using a temp_pointer. If the element is the first element
then there is no problem but if it is in between then what is the best
solution.
From what you have said elsethread, I think what the interviewer may
have been looking for is something like the following trick:
Question:
Given a singly linked list, a pointer to a node a in the list, and a
pointer to a new node n, but no other information, how do you insert
node n before node a in the list?
First thoughts:
This is impossible. You need to find the node before a in the list,
and there is no way to do this if you aren't given a pointer to the
start of the list (or at least, to a node somewhere before a in the
list). Indeed, if a is the first node in the list, you need to be able
to change the pointer to the start of the list (to get it to point to
n).
"Solution":
However, one way of achieving a similar result is as follows. You swap
a and n's data over. Then you add node n (which now has a's data)
after a in the list. Result - the new list has a node with n's data
before a node with a's data. This however is not quite the same as
simply inserting node n before node a - any pointers which pointed to
node a before you started will now be pointing to node n's data
instead.
This technique can be used with similar questions. For instance,
suppose you are given the start of the list - but you are told that
you have to do the insertion in constant time, meaning that you don't
have time to "walk" the list to find the node before a. Or, you could
be told you cannot use any pointers other than the ones to a and n.
This latter question may be the one you were asked.
Hope this is helpful.
Paul.