Reputation: 325
I am trying to sort a LinkedList
in Java. I need to go through mylist
from back to front. The elements in the list are objects from my class CustomElement
. If they match a certain pattern I want to put them up front.
My problem is that if I detect that the element in my list with index 5 for example matches my pattern and I move it to index 0, the previous element with index 4 has index 5 now, right? That is why I want the for loop to check the element with index 5 again: i++
. But that's causing an infinite loop, whreas the method's working fine without i++
, but not the way that I want it, because it's skipping the element with index 4 (now 5).
Is it gernerally possible to raise the variable i
inside the for loop? And if yes, what am I doing wrong.
for (int i = mylist.size() - 1; i >= 0; i--) {
if (mylist.get(i) matches a certain pattern) {
CustomElement helper = mylist.get(i);
mylist.remove(i);
mylist.add(0, helper);
i++;
}
}
Upvotes: 1
Views: 1031
Reputation: 1919
It is, but in your case using get(i) for a linked list will give quadratic performance.
If you don't mind your "matching" items being reversed in order then you'd be better creating a new list:
final LinkedList<CustomElement> newList = new LinkedList<> ();
for (final CustomElement e: myList)
{
if (e matches your pattern) { newList.addFirst (e); }
else { newList.addLast (e); }
}
myList = newList;
Then all problems with index variables disappear...
(You could also achieve linear performance whilst modifying the existing list, but it's a little more complicated.)
Upvotes: 1
Reputation: 31194
Yes, it is possible to modify i
inside your for loop, if it weren't possible, you wouldn't be getting this infinite loop.
What must be happening, is that if (mylist.get(i) matches a certain pattern)
continues to be true after a certain point, and you never get to a point where i >= 0
is not true.
So, if myList.get(0)
matches your pattern, you'll just put it back at index 0
, and keep checking it forever.
Upvotes: 4