如何按整数排序队列

时间:2016-12-04 14:54:40

标签: java

我写了一个队列ADT,但是我需要用整数降序排队。这是我到目前为止所做的代码: 我的队列代码部分:

  public class NewPriorityQueue<T> {

  private Node firstNode = null;
  private Node lastNode = null;
  private int queueLength = 0;

  @Override
  public void enqueue(T newEntry, int priority) {
    Node newNode = new Node(newEntry, priority);
    Node current = firstNode;
    if (current != null && newNode.priority > 0) {
      newNode.next = current;
      current = newNode;
    }
    if (isEmpty()) {
      firstNode = newNode;
      lastNode = newNode;
    } else {
      firstNode = current;
    }
    queueLength++;
  }

测试代码:

public static void main(String[] args) {
    PriorityQueueInterface<Character> queue = new NewPriorityQueue<>();
    queue.enqueue('e');
    queue.enqueue('f',10);
    queue.enqueue('g',20);
    queue.enqueue('h',5);
    System.out.print(queue.dequeue());
    System.out.print(queue.dequeue());
    System.out.print(queue.dequeue());
    System.out.print(queue.dequeue());
  }

应该是预期的结果,但我不知道如何对它进行排序。有没有办法轻松排序队列?

1 个答案:

答案 0 :(得分:0)

您的代码存在的问题是您没有遍历队列

public void enqueue(T newEntry, int priority) {
    Node newNode = new Node(newEntry, priority);
    Node current = firstNode;

    // if queue is empty, just insert the node
    if (current == null) {
        current = newNode;
        newNode.setNext(null);
    } else {
        Item next = current;
        Item prev = next;

        // loop through the queue to find the correct point of insertion
        do {
            if (priority > next.getPriority()) {
                // break and insert
                break;
            }
            prev = next;
            next = next.getNext();
        } while (next != null);

        newNode.setNext(next);
        // the edge case to see if the newNode has greatest priority
        if (newNode.getPriority() > firstNode.getPriority()) {
            current = newNode;
        } else prev.setNext(newNode);
    }
    queueLength++;
}