基于动态数组实现队列
接口
package com.company.queue;
public interface Queue<E> {
int getSize();
boolean isEmpty();
void enqueue(E e);
E dequeue();
E getFront();
}
实现类及测试
package com.company.queue;
import com.company.Array;
/**
* @program: Array
* @description: 数组实现队列,先进先出策略
* @author: Gu
* @create: 2019-04-14 21:23
**/
public class ArrayQueue<E> implements Queue<E>{
private Array<E> array;
public ArrayQueue() {
array = new Array<>();
}
public ArrayQueue(int capacity) {
array = new Array<>(capacity);
}
@Override
public int getSize() {
return array.getSize();
}
@Override
public boolean isEmpty() {
return array.isEmpty();
}
@Override
public void enqueue(E e) {
array.addLast(e);
}
@Override
public E dequeue() {
return array.removeFirst();
}
@Override
public E getFront() {
return array.get(0);
}
@Override
public String toString() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(String.format("ArrayQueue的size: %d, capacity : %d \n",getSize(), array.length()));
stringBuffer.append("front [");
for (int i = 0; i < getSize(); i++) {
stringBuffer.append(array.get(i));
if (i == getSize() - 1) {
stringBuffer.append("] end");
break;
}
stringBuffer.append(",");
}
return stringBuffer.toString();
}
public static void main(String[] args) {
ArrayQueue<Integer> arrayQueue = new ArrayQueue();
for (int i = 0; i < 10; i++) {
arrayQueue.enqueue(i);
}
System.out.println(arrayQueue);
System.out.println(arrayQueue.dequeue());
System.out.println(arrayQueue.getFront());
System.out.println(arrayQueue);
}
}
基于数组实现的队列,在出队的时候,时间复杂度为O(n),我们希望是O(1),从而引入第二部分,循环队列。
网友评论