【发布时间】:2015-07-16 20:40:05
【问题描述】:
我正在尝试从一些无序的原始数据(String1...Priority10、String2...IntPriority2 等)创建一个链接列表,并且在概念化如何排序时遇到了麻烦,我无法为优先级队列编写一个好的方法。我需要获取将每个对象按顺序排入队列的方法,而不是在最终链表上使用排序算法,或者使用任何 LinkedList 或 PriorityQueue 本身。
我的入队方法,这里没什么难的:
public class ObjectQueue{
Object front = null; //points to first element of the queue
Object prev = null; //points to last element of the queue
/**
* Creates an object of Object and adds to the class queue
* @param name of object
* @param rank of priority sort
*/
public void enQueue(String name, int rank)
{
Object current = new Object(name, rank); //uses current entry String as name, int as rank
if(isEmpty()) //if empty, add element to front
{
front = current;
}
else //if elements exist, go to end and create new element
{
prev.next = current;
}
prev = current;
还有我遇到问题的优先排序和添加方法:
/**
* Adds each object and rank on a ascending rank basis
* @param filename name of data file
* @throws exc in case of missing file
*/
public void addPriority(String filename) throws IOException
{
try
{
File inFile = new File(filename); //inst. file import
Scanner read = new Scanner(inFile); //inst. scanner object
String name1 = read.next(); //scanner reads next string, primes at front
int rank1 = read.nextInt(); //reads next int, assigns to rank
while (read.hasNext()) //reads until end of text
{
String name2 = read.next(); //next string of next Object to be tested
int rank2 = read.nextInt(); //rank to test rank1 against
if (rank1 > rank2) //if current is higher priority than test
{
enQueue(name1, rank1); //enqueue the current object
name1 = name2; //move test name down to current
rank1 = rank2; //move test rank down to current
}
else
{
enQueue(name2, rank2); //enqueue the current object
}
}
read.close(); //ends read when empty
}
catch(Exception exec)
{
System.out.println("Error: file not found.");
}
}
我需要一个单一的方法来预先对对象进行排序而不将它们发送到列表中,或者在运行中对它们进行一次正确排序,但我的想法已经用完了。
【问题讨论】:
-
你不需要排序来实现优先队列。你应该阅读堆。另外你为什么使用链表而不是数组?这是非常低效的方法
-
我需要为此使用链表,而不是数组。并且没有 LinkedList 对象,只是我自己的从头开始。
-
然后阅读二进制堆并尝试使用 双重 链表 (en.wikipedia.org/wiki/Heap_%28data_structure%29) 来实现它们
标签: java linked-list priority-queue