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

前端 未结 8 1559
梦毁少年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条回答
  •  旧时难觅i
    2020-12-28 20:33

    The best performance you can get from comparison sorts like merge sort or quick sort is O(nlogn). You can get O(n) performance from non-comparison sorts like radix sort.

    If you are reversing a linked-list, then you can reverse the list in O(n) time with using just 3 extra items. You need 3 pointers to keep track of what you're currently pointing to, what is before your current item and what is after your current item. The code is:

    Node current = head;
    Node next = null;
    Node prev = null;
    while (current != null) {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
    return prev;
    

提交回复
热议问题