X387: LinkedQueuePriorityEnqueue

For the question below, assume the following implementation of LinkedQueue:


public static final class LinkedQueue<T> implements QueueInterface<T> {
    private Node<T> firstNode;
    private Node<T> lastNode;

    public LinkedQueue() {
        firstNode = null;
        lastNode = null;
    }


    @Override
    public T getFront() {
        if (isEmpty()) {
            return null;
        }
        return firstNode.getData();
    }


    @Override
    public boolean isEmpty() {
        return firstNode == null;
    }


    @Override
    public void clear() {
        firstNode = null;
        lastNode = null;

    }

    public class Node<E> {
        private E data; // Entry in bag
        private Node<E> next; // Link to next node

        public Node(E dataPortion) {
            this(dataPortion, null);
        } // end constructor


        public Node(E dataPortion, Node<E> nextNode) {
            data = dataPortion;
            next = nextNode;
        } // end constructor


        public E getData() {
            if (data != null) {
                return data;
            }
            return null;
        }


        public Node<E> getNext() {
            return next;
        }


        public void setNext(Node<E> newNext) {
            next = newNext;
        }

} // end LinkedQueue

Your task is to create a "priority" enqueue method. If something is enqueued, it normally goes to the back of the line, but in this method it will go to the front of the line.

For example, if you had a linked queue that looked like:

(firstNode) 1 --> 2 --> 3 (lastNode)

and you ran priorityEnqueue(4)

the result would be:

(firstNode) 4 --> 1 --> 2 --> 3 (lastNode)

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.