PDA

View Full Version : Traversing a LinkedList in Java


redundant
05-20-2005, 03:56 AM
Hey,

So I've got a LinkedList that I need to traverse through. Right now I'm going through it the same way that I would for a regular array, which works, it's just very slow. That is:

for (int i = 0; i < list.size(); i++)
{
code;
}


Can anyone help me with the correct way to go through the entire list?

obiwanjabroni
05-24-2005, 02:57 PM
Read up on the Iterator class. It will point to the head of the linked list, so you will be able to move to the next element with the Next() method.

Your code also breaks down since you do not know where the beginning of the list is and you make no attempt to find it before starting your for loop at 0.

suryad
05-28-2005, 08:50 AM
obiwanjabroni is quite right...iterators are your friends in Java...saved me a lot of trouble actually.