使用双向链接列表为自定义优先级队列创建某种排队方法

时间:2016-05-09 00:41:04

标签: java priority-queue comparable doubly-linked-list

我在DoublyLinkedList类中创建了以下add方法:

    /**
     * This method adds a DoublyLinkedNode at the end of the list.
     * @param element
     */
    public void add(E element) {
        DoublyLinkedNode <E>  newNode = new DoublyLinkedNode <E>(element);

        if (head == null) {
          head = tail = newNode; // The new node is the only node in list
        }
        else {
          tail.setNext(newNode); // Link the new with the last node
          tail = tail.getNext(); // tail now points to the last node
        }

        size++; // Increase size
      }

public void  add (int index,E element) {
  // Checking if index is out of bound and then throwing exception.
    if (index < 0 || index >= size)
        throw new IndexOutOfBoundsException("Index is out of bound.");
  // Checking if the list is empty and then adding the element to the head.
    if(head == null)
        head.setElement(element);
  // Creating a temporary node and assigning head to it.
    DoublyLinkedNode <E> tmp = head;
 // If the index exists in the first half then search starts from head.
    if(index <= size/2) {
        for(int i =0; i <index; i++)
            tmp = tmp.getNext();
    }

  // If the index exists in the second half then search starts from the tail.
    if(index > size/2) {
        tmp = tail;
        for(int i =size-1; i >index; i--)
            tmp = tmp.getPrevious();
        }
    // Setting the node element found at the index to the given element.
    tmp.setElement(element);

    }

现在我想创建一个优先级队列,其中最小值元素具有最高优先级(与传统优先级队列相反)。我通过以下方式创建了我的优先级队列排队方法:

public class PriorityQueue <E extends Comparable <E>>
{
    private DoublyLinkedList <E> elements;
// ----------------------------------------------------------
/**
 * Create a new PriorityQueue object.Inistantiates elements.
 */
public PriorityQueue() {
    elements = new DoublyLinkedList();
}

public void enqueue(E element) {
   /* for(int i =0; i < elements.size();i++)
   if(element.compareTo(elements.get(i))<0) */
    elements.add(element);
}

我真的不知道是否正确的方法是比较队列中的任何给定元素以找到它的顺序然后将其添加到队列中。我的意图是从文件中读取任何内容然后按顺序输出它们。

0 个答案:

没有答案