您的位置:首页 > 其它

顺序队列(数组实现)

2015-10-05 19:10 239 查看
下面利用数组实现的循环队列,并考虑了上溢出和下溢出。

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: