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

前端 未结 8 1564
梦毁少年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:19

    You already know the length. So just use 1 temporary variable and start at index 0 and go on swapping list[0] and list[length -1], then list[1] and list[length-2], and so on. O(n) time and O(1) space for 1 temporary variable.

    EDIT: Just noticed you assume O(n) for accessing the middle of the list. oh well. nevermind.

    alternatively, store the next/previous pointers of the two elements you swapped to move towards the middle (assuming it's a doubly linked list). Then you get O(n) time.

提交回复
热议问题