user478984
user478984

Reputation: 43

Trying to jump directly to a node in a linked list

Hello I dont know if there is a command in C++ which I can use to jump directly to 5th node in a linked list? I know with : p->next i can try to go to the next node but what if I want to go to the 56th right awat is there a way ? like p->next(56) or something ? Thanks

Upvotes: 2

Views: 1775

Answers (5)

phlipsy
phlipsy

Reputation: 2949

At least if you have an iterator of the category InputIterator (those of std::list are of this category) you can use std::advance. For example, if you want to get the iterator pointing to the fifth element from the beginning of the list:

std::list<int> l;
// ...
std::list<int>::iterator it = l.begin();
std::advance(it, 4);
// Now it points to the fifth element

But as the others already mentioned: A linked list isn't supposed to have random access. You always have to travel through it in order to get a certain entry. And thus std::advance will perform very poor for large lists.

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67345

There is no such "command". A characteristic of a linked list is that it is slower to locate a particular node by position. Unless of course, you've already stored a pointer to that node.

If this is a problem, then a linked list is not the correct data structure for your purposes.

Upvotes: 2

wilhelmtell
wilhelmtell

Reputation: 58715

This is the nature of linked lists. You'll have to traverse all the way to the nth element.

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106236

C++ doesn't provide a linked list type that you can access at that level. It does have std::list<>, which provides encapsulation. You can not directly index into a linked list... though you can advance 56 steps from the first (or some other already-found) element, but each node must be traversed and this is relatively inefficient. If you need better performance, you should reconsider your choice of container: perhaps a vector or map would be more appropriate.

Upvotes: 0

WuHoUnited
WuHoUnited

Reputation: 8429

If the linked list does not have a command like p->get(56) built in then you have to write your own function that uses a for loop. It takes the list and the number of the element you want and then calls next that number of times.

Upvotes: 3

Related Questions