Answer to Question #318384 in Java | JSP | JSF for Suman

Question #318384

Implement your own version of the priority queue data structure using java with OOPs principles mentioned functionalities: enqueue, Dequeue (highest priority), peek(highest priority), contains, size, center, sort reverse, iterator, traverse/print.

Use of similar data structures already present in the language/framework is not allowed.


1
Expert's answer
2022-03-27T11:38:06-0400
// Queue.java

public class Queue<T> {

    private Node<T> head;
    private Node<T> tail;



    private int count = 0;

    public void enqueue(T t){
        Node<T> node = new Node<>(t);


        if(head == null){
            head = node;
        }

        if(tail != null){
            tail.next = node;
        }
        tail = node;
        count++;
    }

    public void dequeue(){
        head = head.next;

        if(head == null){
            tail = null;
        }
        count--;
    }

    public T peek(){
        return head.value;
    }

    public void contains(){

    }

    public int size(){
        return count;
    }

    public void center(){

    }

    public void sortReverse(){

    }

    public void print(){

    }


    private static class Node<T>{
        private final T value;
        private Node<T> next;
        private Node<T> back;

        public Node(T value){
            this.value = value;
        }

    }
}

// Main.java
public class Main {


    public static void main(String[] args) {

        Queue<String> queue = new Queue<>();

        queue.enqueue("A");
        queue.enqueue("B");
        queue.enqueue("C");
        queue.enqueue("D");

        System.out.println(queue.peek());
        queue.dequeue();
        System.out.println(queue.peek());
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS