how to reverse a list with O(1) space and O(n) time?

前端 未结 8 1555
梦毁少年i
梦毁少年i 2020-12-28 19:56

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

8条回答
  •  长发绾君心
    2020-12-28 20:28

    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.

提交回复
热议问题