Firstly I feel I should mention this is for an assignment. I\'m not looking for a direct code answer just to point me in the right direction. We have been asked to implement a P
Here is some pseudocode code. (I have tested it by creating a queue)
public void insert(int priority, int data) {
Item item = new Item(priority, data);
if (head == null) {
head = item;
item.setNext(null);
} else {
Item next = head;
Item prev = next;
do {
if (priority > next.getPriority()) {
// break and insert
break;
}
prev = next;
next = next.getNext();
} while (next != null);
item.setNext(next);
if (item.getPriority() > head.getPriority()) {
head = item;
} else prev.setNext(item);
}
}
You had the following problems in your insert method:
prev = head;
head.setNext(head);
prev = pqItem;
What does this piece of code even do? Here is what it does:
You also did not consider the case in which you have more than two items in the queue. Imagine you have 5 items in the queue. And now you want to insert pqItem
in the queue. pqItem
has the least priority so it will get inserted at the end of the queue, right? Therefore, you need to traverse the queue (list) in order to get to the last item.