Reputation: 319
This was asked in an IBM ISL interview.
I went through the question, How to find the middle node of a single linked list in a single traversal (if the length of the list is not given) but it does not contain the answer I am looking for so posting here again.
I have a single linked list, let us say number of nodes are odd. Tell me 2 ways of finding middle node by traversing list only once?
I answered, take 2 pointers p1 & p2 move p2 by 2 nodes and p1 by 1 node. When p2 is null, p1 is at middle node.
Interviewer responded: That’s the simplest way using 2 pointers. Tell me one more way. Hint: is there a compiler property that can be used?
Can someone give me a way using the hint?
Upvotes: 0
Views: 1031
Reputation: 71525
#include <vector>
#include <list>
typedef std::list<int> listT;
listT::const_iterator
find_middle(const listT &list)
{
std::vector<listT::const_iterator> v;
for (listT::const_iterator i = list.begin() ; i != list.end() ; ++i)
v.push_back(i);
return v[v.size() / 2];
}
Upvotes: 5