码迷,mamicode.com
首页 > 编程语言 > 详细

顺序队列(数组实现)

时间:2015-10-05 19:34:49      阅读:117      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!