首页 > 编程语言 > 详细

顺序队列(数组实现)

时间:2015-10-05 19:32:44      阅读:191      评论:0      收藏:0      [点我收藏+]

下面利用数组实现的循环队列,并考虑了上溢出和下溢出。

public class Queue {
    private int[] queue;
    private static final int defaultSize = 100;
    private int size;
    private int tail, head;
    public Queue() {
        setUp(defaultSize); 
    }
    public Queue(int sz) {
        setUp(sz);
    }
    public void setUp(int sz) {
        size = sz; tail = 0; head = 0; queue = new int[size];
    }
    public void enqueue(int x) throws Exception {
        if(isFull()) throw new Exception("overflow");
        else {
            queue[tail%size] = x;
            tail++;
        }
    }
    public int dequeue() throws Exception {
        if(isEmpty()) throw new Exception("underflow");
        else {
            int val = queue[head%size];
            head++;
            return val;
        }
    }
    public int peek() throws Exception {
        if(isEmpty()) throw new Exception("underflow");
        else return queue[head%size];
    }
    public boolean isEmpty() {
        return tail == head;
    }
    public boolean isFull() {
        return (tail + 1)%size == head%size; //设置浪费一个存储空间单元,即head所指的位置仍空闲。
    }
    public void clear() {
        tail = head = 0;
    }
}

 

顺序队列(数组实现)

原文:http://www.cnblogs.com/lasclocker/p/4856125.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!