基于自己的理解实现循环队列
来源:3-7 循环队列的实现
颠覆123
2021-02-01
老师好,这是基于我自己的理解写的循环队列,也就是数组中第一个元素的下标是front,数组中最后一个元素的下标是tail,代码如下:
public interface Queue {
public int getSize();
public int getCapacity();
public boolean isEmpty();
public E front();
public void enqueue(E e);
public E dequeue();
}
public class MyLoopQueue implements Queue {
private E[] data;
private int front;
private int tail;
private int size;
public MyLoopQueue(int capacity) {
data = (E[])new Object[capacity];
}
public MyLoopQueue() {
this(10);
}
@Override
public int getSize() {
return size;
}
@Override
public int getCapacity() {
return data.length;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public E front() {
if(isEmpty()) {
throw new IllegalArgumentException(“还没有向队列添加元素。”);
}
return data[front];
}
@Override
public void enqueue(E e) {
if(tail == data.length - 1 || (front == tail && front != 0 && tail != 0)) {
resize(getCapacity() * 2);
}
data[tail + 1] = e;
tail = ++tail % data.length;
size++;
}
private void resize(int newCapacity) {
E[] newData = (E[])new Object[newCapacity];
for (int i = 0; i < size; i++) {
newData[i] = data[(front + i) % data.length];
}
data = newData;
newData = null;
front = 0;
tail = size - 1;
}
@Override
public E dequeue() {
if(isEmpty())
throw new IllegalArgumentException(“Cannot dequeue from an empty queue.”);
E res = data[front];
data[front] = null;
front = (front + 1) % data.length;
size--;
if(size == getCapacity() /4 && getCapacity() / 2 != 0) {
resize(getCapacity() / 2);
}
return res;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append(String.format(“Loop queque size = %d, capacity = %d\n”, size, getCapacity()));
for (int i = front; i == tail && front != 0 && tail != 0; i = (i + 1) % data.length) {
res.append(data[i]);
if((i + 1) % data.length != tail) {
res.append(",");
}
}
return res.toString();
}
public static void main(String[] args) {
LoopQueue lq = new LoopQueue<>();
for (int i = 0; i < 10; i++) {
lq.enqueue(i);
System.out.println(lq);
if(i % 3 == 2) {
lq.dequeue();
System.out.println(lq);
}
}
}
}
麻烦老师有空看看我这样写是否可以。辛苦了老师,我问的问题不少。
1回答
-
liuyubobobo
2021-02-01
是不是这里的讨论就是你的逻辑:http://coding.imooc.com/learn/questiondetail/220313.html
等你学习了 BST 以后,可以应用自己写的队列,实现一个 BFS,之后提交给 Leetcode,让 Leetcode 帮助你测试。课程中会经常使用这种方法来测试我们自己写的数据结构:)
继续加油!:)
022021-02-01
相似问题