0

I'm struggle in finding the algorithm for letting the method remove the element on the specific index if someone can help

I've tried implement some below but it's probably wrong in term of logic I also got the javadoc so that you know what the algorithm ask

 /**
         * Removes and returns the element that is at place x in the queue.
         * Precondition: x must be less than 5, x must be less than size Note:
         * indexing from 0: 0 == front element, 1 == second element, etc.
         *
         * @param x the passed in index of the element to be removed
         * @return the element removed from the queue
         * @throws EmptyCollectionException if the queue is empty
         * @throws InvalidArgumentException if x > 4, or x > size of collection
         *
         */
        //@Override
    public T dequeue(int x) throws EmptyCollectionException, InvalidArgumentException {
        // exception throw if queue is empty
        if (numNodes == 0) {
            throw new EmptyCollectionException("Empty Collection");
        }
        // exception throw if x > 4 or size
        if (x > 4 || x > size()) {
            throw new InvalidArgumentException("Invalid x");
        }
        T result = null;
        LinearNode<T> temp = front;
        int count;
        while (temp != null) {
            result = temp.getElement();
            if (numNodes == 1) {

                front = null;
                back = null;
                numNodes--;
                return result;
            }
            if (numNodes > 1) {
                if (count == x) {
                    result = result.setNext();
                }
                x++;
                front = temp.getNext();
                front.setPrev(null);
                numNodes--;
                return result;
            }
        }

remove the node of index x

Dave Phan
  • 31
  • 4

1 Answers1

0

Assuming Your 'LinearNode' class works something like a LinkedList and has getPrevious() and getNext() methods:

public T dequeue(int idx) {
    // Any other bounds checks go here
    LinearNode<T> curNode = front;
    for(int i = 0; i < idx; i++) {
        if(curNode.getNext() != null) {
            curNode = curNode.getNext();
        } else {
            // idx is out of bounds
            throw new InvalidArgumentException("Index is out of bounds");
        }
    }
    LinearNode<T> previousNode = curNode.getPrevious();
    LinearNode<T> nextNode = curNode.getNext();
    if(previousNode != null) {
        previousNode.setNext(nextNode);
    }
    if(nextNode != null) {
        nextNode.setPrevious(previousNode);
    }
    if(curNode.equals(front)) {
        front = nextNode;
    }
    if(curNode.equals(back)) {
        back = previousNode;
    }
    return curNode.getElement();
}
Steve
  • 981
  • 1
  • 8
  • 22