Priority queue implementation using a linked list.

public class PriorityQueue {
    private LinkedList list; 
    
    public PriorityQueue() {
	list = new LinkedList();
    }
    
    public boolean isEmpty() {
	return list.isEmpty();
    }
    
    public void enqueue(int k) {
	Node newNode = new Node(k);
	Node n = list.getFirst();
	if(n == null || k >= n.getData()) {
	    list.addFront(newNode);
	}
	else {
	    while (n.getNext() != null && k < n.getNext().getData()) {
		n = n.getNext();
	    }
	    newNode.setNext(n.getNext());
	    n.setNext(newNode);
	}
    }
    
    public int dequeue() {
	if (list.isEmpty()) {
	    System.out.println("Trying to dequeue an empty queue");
	    System.exit(0);
	}
	int data = list.getFirst().getData();
	list.removeFront();
	return data;
    }
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.