简体   繁体   中英

Removing/undoing a node in doubly linked list

I know the time complexity for removing a node in a doubly linked list is O(1). I've seen a lot of examples of code where people use a loop in remove method in doubly linked list and still the time complexity is O(1). I've written a code which undoes, ie removes a node in a doubly linked list but my question is: would my code undo/remove a node in a O(1) in undo() method as I call getNode() method that contains a loop? I'd appreciate explanations! Thanks in advance!

private Node <T> getNode( int idx ){
        return getNode( idx, 0, size( ) - 1 );
    }
private Node<T> getNode( int idx, int lower, int upper ){
        Node<T> p;
        if( idx < lower || idx > upper ){
            throw new IndexOutOfBoundsException( "getNode index: " + idx + "; size: " + size( ) );
        }
        if( idx < size( ) / 2 )
        {
            p = beginMarker.next;
            for( int i = 0; i < idx; i++ )
                p = p.next;            
        }
        else
        {
            p = endMarker;
            for( int i = size( ); i > idx; i-- )
                p = p.prev;
        } 
        return p;
    }
public void undo(){
        if(isEmpty()){
            throw new RuntimeException("Undo history is empty");
        }
        else{
            T data = undoStackDatas.topAndPop();
            int index = undoStackIndexes.topAndPop();
            //Push data and index back into redo stacks
            redoStackDatas.push(data);
            redoStackIndexes.push(index);

            Node<T> obj = getNode(index);
            if(obj == beginMarker){
                beginMarker = obj.next;
            }
            else{
                obj.prev.next = obj.next; 
            }

            if(obj == endMarker){
                endMarker = obj.prev;
            }
            else{
                obj.next.prev = obj.prev;
            }
            theSize--;
            modCount--;
        }
    }

Removal of a node from a double linked list is O(1) if you are given the node you must delete.

But in that case that you must search for the node, then your complexity will change due to the searching. In this case your complexity will change to O(n).

you will have added time-complexity of for loop because when you trace the execution path of the code, you need to traverse those for loops to fully execute your for loop. you just cant decrease the time complexity using a method call, because during your program execution all the statements that is executed is counted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM