下面利用数组实现的循环队列,并考虑了上溢出和下溢出。
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; } }
时间: 2024-12-22 23:49:49