使用了循环数组实现的,所以时间复杂度和空间复杂度都是O(1)
队列实现类长这样
package NodeTest;
/**
* @ClassName MyQuque
* @Description TODO
* @Author 14784
* @Date 2020/6/21 21:55
* @Version 1.0
*/
public class MyQuque {
private int array[]; //存放队列的循环数组
private int front; //队头下标
private int rear; //队尾下标
public MyQuque(int capcacity) {
this.array = new int[capcacity];
}
/**
* 入队
* @param element 入队元素
* @throws Exception
*/
public void enQueue(int element) throws Exception{
if ((rear+1)%array.length==front){
throw new Exception("队列已满!");
}
array[rear] = element;
rear = (rear+1)%array.length; //小数取模大数得本身
}
/**
* 出队
* @return dequeeuElement 出队元素
* @throws Exception
*/
public int deQueue () throws Exception{
if (rear == front){
throw new Exception("队列为空!");
}
int dequeueElement = array[front]; //取出元素
front = (front+1)%array.length; //对头位置改变
return dequeueElement;
}
/**
* 输出队列
*/
public void output(){
for (int i = front ;i!=rear;i = (i+1)% array.length){
System.out.print(array[i]+",");
}
System.out.println();
}
}
main方法:
package NodeTest;
/**
* @ClassName main
* @Author 14784
* @Date 2020/6/3 17:38
* @Version 1.0
*/
public class main {
public static void main(String[] args) throws Exception{
/**
* 队列
*/
MyQuque myQuque = new MyQuque(6);
System.out.println("入队元素为");
myQuque.enQueue(3);
myQuque.enQueue(5);
myQuque.enQueue(6);
myQuque.enQueue(8);
myQuque.enQueue(1);
myQuque.output();
System.out.println("出队后");
myQuque.deQueue();
myQuque.deQueue();
myQuque.deQueue();
myQuque.output();
System.out.println("重新入队新元素");
myQuque.enQueue(2);
myQuque.enQueue(4);
myQuque.enQueue(9);
myQuque.output();
}
}