I am looking for a method that reverses the same instance of a given list, with O(1) additional space and O(n) time.
this is not HW nor I am looking for some library me
The ListIterator
interface is what you're looking for (under the reasonable assumption that the list in question fully supports it; both ArrayList
and LinkedList
do):
ListIterator fwd = list.listIterator();
ListIterator back = list.listIterator(list.size());
while (fwd.nextIndex() < back.previousIndex()) {
T tmp = fwd.next();
fwd.set(back.previous());
back.set(tmp);
}
Even on linked lists, this should be linear in time.