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

前端 未结 8 1552
梦毁少年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:35
       public LinkedList Reverse(LinkedList head)
    {
        if (head == null) return null; // first question
    
        if (head.Next == null) return head; // second question
    
        // third question
        // so we grab the second element (which will be the last after we reverse it)
    
        LinkedList secondElem = head.Next;
    
        // bug fix - need to unlink list from the rest or you will get a cycle
        head.Next = null;
    
        // then we reverse everything from the second element on
        LinkedList reverseRest = Reverse(secondElem);
    
        // then we join the two lists
        secondElem.Next = head;
    
        return reverseRest;
    }
    
    0 讨论(0)
  • 2020-12-28 20:37

    using ListIterators:

    ListIterator<T> head = list.listIterator();
    ListIterator<T> tail = list.listIterator(size);//assuming this can be done in O(1) though O(n) doesn't hurt that much and total is still O(n)
    while(head.nextIndex()<tail.previousIndex()){
        T tmp = head.next();
        head.set(tail.previous());
        tail.set(tmp);
    }
    
    0 讨论(0)
提交回复
热议问题