如何为自定义类迭代优先级队列

时间:2016-06-15 09:34:16

标签: android

您好我正在开发一个蛇游戏,我想将蛇运动点存储在优先级队列中,但我没有得到如何遍历该优先级队列 下面是我的Priority Queue类和Point类来存储点

优先级队列类:

 public class PriorityQueue {

    private Points[] heap;
    private int heapSize,capacity;
    /** Constructor **/
    public PriorityQueue(){
        heapSize = 0;

    }
    public void setCapacity( int capacity)

    {
        this.capacity = capacity + 1;
        heap = new Points[this.capacity];

    }
    /** function to clear **/
    public void clear()
    {
        heap = new Points[capacity];
        heapSize = 0;

    }
    /** function to check if empty **/
    public boolean isEmpty()
    {
        return heapSize == 0;
    }
    /** function to check if full **/
    public boolean isFull()
    {

        return heapSize == capacity - 1;
    }

    /** function to get Size **/
    public int size()
    {
        return heapSize;
    }

    // method to insert point

    public void insert(float x, float y, float rotation, int priority)
    {

        Points points = new Points(x,y,rotation,priority);
        heap [++heapSize] = points;

        int pos = heapSize;
        while (pos != 1 && points.priority > heap[pos/2].priority)
        {
            heap[pos] = heap[pos/2];
            pos /=2;
        }
        heap[pos] = points;

    }

    // function to remove point

    public Points remove()
    {
        int parent, child;
        Points item, temp;
        if (isEmpty() )
        {
            System.out.println("Heap is empty");
            return null;
        }
        item = heap[1];
        temp = heap[heapSize--];
        parent = 1;
        child = 2;
        while (child <= heapSize)
        {
            if (child < heapSize && heap[child].priority < heap[child + 1].priority)
                child++;
            if (temp.priority >= heap[child].priority)
                break;

            heap[parent] = heap[child];
            parent = child;
            child *= 2;
        }
        heap[parent] = temp;
        return item;
    }
}

点类:

public class Points {

    private float X;
    private float Y;
    int priority;
    private float rotation;

   public Points(float x, float y,float rotation,int priority)
   {

       this.X = x;
       this.Y = y;
       this.rotation = rotation;
       this.priority = priority;


   }

    public float getX() {
        return X;
    }

    public float getY() {
        return Y;
    }

    public float getRotation() {
        return rotation;
    }

    public int getPriority() {
        return priority;
    }
}

请指导我如何遍历此队列类。 提前谢谢

0 个答案:

没有答案