I'm trying to make a PriorityQueue without using the PriorityQueue class provided by Java. For this, I have some given methods that I have to fill in. I'm not sure where I'm making the mistake. It seems that my put and get functions are both wrong, and I'm not sure how to make a new PQ as is given in the code. What I have is the following:
class Element {
private int priority;
private String data;
Element(int priority, String data) {
// Ihr Code
this.priority = priority;
this.data = data;
}
public String getData() {
// Ihr Code
return data;
}
public int getPriority() {
// Ihr Code
return priority;
}
/**
* Return data and priority as string
* Format: Data (Priority)
* e.g: abc (7)
*/
public String toString() {
String str = data + " " + Integer.toString(priority) + ")";
return str;
}
}
public class PriorityQueue {
static final int SIZE = 32;
private Element[] data = null;
// actual number of entries
private int len = 0;
/**
* Creates a new PriorityQueue
*/
public PriorityQueue() {
// Ihr Code
}
/**
* Adds a new element into the queue as long as there is space
* Returns true if element could be added, otherwise false
*/
boolean put(Element element) {
// Ihr Code
if(len == SIZE){
return false;
}else{
int i = len-1;
while (i>=0 && element.getPriority() > data[i].getPriority()){
data[i+1] = data[i];
i--;
}
data[i+1] = element;
len++;
return true;
}
}
/**
* Returns element with the highest priority
* and removes it from the queue. Otherwise returns null
*
*/
Element get() {
// Ihr Code
if (len > 0){
Element x = q[0];
for(int i = 1; i < len; i++){
data[i-1] = data[i];
}
len--;
return x;
}else{
return null;
}
}
/**
* Number of entries
*/
int length() {
// Ihr Code
return len;
}
/**
* Returns contents of the queue as a String
* Format: data1 (priority1), data2 (priority2)
* e.g: abc (7), cde (8)
* Attention: There should be no comma at the end of the String
*/
public String toString() {
// Code
String res = new String();
//res = "(" + data + "," + ")";
if(data.length>0){
StringBuilder sb = new StringBuilder();
for(String s: data){
sb.append(s).append(",");
}
res = sb.deleteCharAt(sb.length()-1).toString;
}
return res;
}
I'm also struggling with the final toString method, to return the queue as a String in the format given, I tried something with a StringBuilder, but this doesn't compile correctly. Alternatively, I could make it with a normal for loop, but again I'm struggling with the exact syntax.
I found resources on the net to build this PQ with heap structures (which I have not had yet) and with a class called Comparator that I failed to understand. Any help would be much appreciated!
I'm mainly struggling with the
public PriorityQueue(){
//what code?}
function. How am I supposed to make a "new" PQ here? Is it supposed to be
PriorityQueue pq = new PriorityQueue();
I'm quite lost! Thanks so much for the help.