Priority Queue

Priority queue using stack

Pinterest LinkedIn Tumblr

A priority queue is a data structure with each element associated with priority information. The high priority served before an element with low priority.

Write a program to implement Priority queue using stack

Algorithm Explanation

Pass array of elements to the utility function.
Add operation insert the element in the priority queue.
Pool operation removes the element from the priority queue. The pool operation displays the removed elements.

Source Code

package com.dsacode.DataStructre.priorityqueue;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;
 
public class PriorityQueueStack {
    private Stack < Integer > st;
    private ArrayList < Integer > list;
 
    public PriorityQueueStack() {
        st = new Stack < Integer >();
        list = new ArrayList < Integer >();
    }
 
    public void add(int e) {
        list.add(e);
 
    }
 
    public int poll() {
        if (!list.isEmpty())
            sortListAndTransferToStack();
        System.out.print(st.peek() + " ");
        return st.pop();
 
    }
 
    private void sortListAndTransferToStack() {
        Collections.sort(list, Collections.reverseOrder());
        st.clear();
        for (int i = 0; i < list.size(); i++) {
            st.push(list.get(i));
        }
        list.clear();
    }
 
    public boolean isEmpty() {
        return st.isEmpty();
    }
 
    public static void main(String[] args) {
 
        Integer[] array = { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 };
        System.out.println("Array of items for insert Priority Queue: "
                + Arrays.toString(array));
 
        PriorityQueueStack heap = new PriorityQueueStack();
 
        for (int i : array) {
            heap.add(i);
        }
 
        System.out.print("Array of items Peek from Priority Queue: ");
 
        for (@SuppressWarnings("unused") int i : array) {
            heap.poll();
        }
 
    }
 
}

Output

Array of items for insert Priority Queue: [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
Array of items Peek from Priority Queue: 1 2 3 4 7 8 9 10 14 16

Write A Comment