user2901181
user2901181

Reputation: 343

Trying to implement a priority queue with an ordered linked list

So what I'm trying to do is implement a priority queue using an ordered linked list. I feel like I am fairly close but I can't seem to resolve the error in the while statement within the insert function. Here's what I have so far:

class OrderedLinkedListMaxPQ<Item> {

private class PQNode {
    Object data; 
    PQNode next;

    public PQNode(Object value) {
        data = value;
        next = null;
    }
}

PQNode head;

public void PriorityQueue() { 
    this.head = null; 
}

public boolean isEmpty() { return this.head == null; }

public void insert(Object item) {

   PQNode prev = null;
   PQNode current = this.head;
   while (current != null && current.data >= item.data) {
       prev = current;
       current = current.next;
   }

   PQNode temp = new PQNode(item);
   if (prev == null) {
       temp.next = this.head;
       this.head = temp;
   } else {
       temp.next = current;
       prev.next = temp;
   }   
}

public Object delete() {
   Object temp = this.head.data;
   this.head = this.head.next;
   return temp;
}

public static void main(String[] args) {
    OrderedLinkedListMaxPQ<Integer> pq = new OrderedLinkedListMaxPQ<Integer>();
    pq.insert(7);
    pq.insert(6);
    pq.insert(3);
    pq.insert(2);
    while (!pq.isEmpty())
        StdOut.println(pq.delete());
   }
}

Upvotes: 0

Views: 2149

Answers (1)

rolfl
rolfl

Reputation: 17707

current.data >= item.data makes no sense. The data is an Object reference and you cannot compare them. Perhaps, if the dat avalues are Comparable you can use the compareTo(...) method. Otherwise you will need to write your own mechanism to compare them. Also, item is passed in as an Object, but you references it as a PNode ... this is a problem too.

Upvotes: 1

Related Questions