【发布时间】:2019-11-05 17:45:41
【问题描述】:
我正在尝试在不使用 Java 提供的 PriorityQueue 类的情况下制作 PriorityQueue。为此,我有一些必须填写的给定方法。我不确定我在哪里犯了错误。看来我的 put 和 get 函数都是错误的,我不确定如何按照代码中给出的方式制作新的 PQ。我有以下内容:
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;
}
我也在努力使用最终的 toString 方法,以给定格式将队列作为字符串返回,我尝试了使用 StringBuilder 的方法,但这不能正确编译。或者,我可以使用普通的 for 循环来实现它,但我又在为确切的语法苦苦挣扎。
我在网上找到了使用堆结构(我还没有)和一个我无法理解的名为 Comparator 的类来构建这个 PQ 的资源。任何帮助将不胜感激!
我主要是在挣扎
public PriorityQueue(){
//what code?}
功能。我应该如何在这里制作“新”PQ?应该是
PriorityQueue pq = new PriorityQueue();
我很迷茫!非常感谢帮忙。
【问题讨论】:
-
你看过最大堆数据结构吗?这对于这个实现很有用。
标签: java class queue priority-queue