概述
使用数组方式创建一个队列,该队列有:
- enqueue() 该方法在队列末尾添加元素 O(1)
- dequeue() 从队列开头移出一项 O(1)
- peek()得到队列第一项,但不删除 O(1)
- isEmpty()
- isFull
准备工作
创建两个指针用来标记下标位置,一个为front,一个为rear,当添加元素时,指针rear后移一位,由于要提高内存效率,于是产生了循环队列,rear并不是一味的自增,而是通过 (rear+1)%数组长度 的关系循环索引。
int[] item;
int count;
int rear;
int front;
public ArrayQueue(int length){
item = new int[length];
}
- enqueue
public void enqueue(int input){
if(isFull())
throw new IllegalStateException();
//每添加一个元素,指针rear向后移动
item[rear] = input;
rear = (rear+1)%item.length;
count++;
}
- dequeue
public int dequeue (){
if(isEmpty())
throw new IllegalStateException();
var it = item[front];
item[front]=0;
front = (front+1)%item.length;
count--;
return it;
}
- peek
//得到队列中第一项元素,但不删除元素
public int peek(){
if(isEmpty())
throw new IllegalStateException();
rear = (rear+1)%item.length;
var pe = item[rear-1];
count--;
return pe;
}
- isEmpty
public boolean isEmpty(){
return count==0;
}
- isFull
public boolean isFull(){
return item.length==count;
}
- toString
@Override
public String toString(){
return Arrays.toString(item);
}
}
show
ArrayQueue aq = new ArrayQueue(5);
aq.enqueue(10);
aq.enqueue(20);
aq.enqueue(30);
aq.enqueue(40);
aq.dequeue();
aq.dequeue();
aq.enqueue(50);
aq.enqueue(60);
aq.enqueue(70);
aq.dequeue();
System.out.println(aq);
最后
以上就是踏实烧鹅为你收集整理的构建队列--使用数组方式的全部内容,希望文章能够帮你解决构建队列--使用数组方式所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复