简体   繁体   中英

Given a single linked list with an odd number of nodes, what are 2 ways of finding middle node by traversing list only once?

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?

#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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM