队列
1 队列:queue,简称队,它同堆栈⼀样,也是⼀种运算受限的线性表,其限制是仅允许在表
的⼀端进⾏插⼊,⽽在表的另⼀端进⾏删除
2 先进先出(即,存进去的元素,要在后它前⾯的元素依次取出后,才能取出该元素)。例
如,⼩⽕⻋过⼭洞,⻋头先进去,⻋尾后进去;⻋头先出来,⻋尾后出来。
**3 队列的⼊⼝、出⼝各占⼀侧。**例如,下图中的左侧为⼊⼝,右侧为出⼝
队列常用方法
- boolean empty() 判断这个队列是否为空
- int peek()返回队首元素,但不出队列
- int poll()返回队首元素,并且出队列
- offer()将指定的元素插入此队列(如果立即可行且不会违反容量限制),插入成功返回 true;否则返回 false。当使用有容量限制的队列 时,offer方法通常要优于 add方法——add方法可能无法插入元素,而只是抛出一个 IllegalStateException异常
- void add(int item); // 将 item 放入队列中
- int size(); // 返回元素个数
底层代码实现
package date;
import java.util.Arrays;
/*数组实现对列*/
public class MyQueue {
private int size = 0;
Object[] queue;
public MyQueue() {
queue = new Object[10];
}
public boolean empty() {
if (size == 0) {
return true;
}
return false;
}
public void extendCapacity(int size) {
if (size > queue.length) {
size += size >> 1;//扩容原来的一半
queue = Arrays.copyOf(queue, size);
}
}
public void add(Object o) {
extendCapacity(size + 1);
queue[size] = o;
size++;
}
public Object poll() {
//Object src:the source array. 源数组
//int srcPos:starting position in the source array. 在源数组中,开始复制的位置
//Object dest:the destination array. 目标数组
//int destPos:starting position in the destination data. 在目标数组中,开始赋值的位置
//int length:the number of array elements to be copied. 被复制的数组元素的数量
Object o = queue[0];
System.arraycopy(queue, 1, queue, 0, size - 1);
size--;
return "删除队列第一个元素" + o;
}
public Object peek() {
Object o = null;
if (!isEmpty()) {
o = queue[0];
}
return "队列头元素" + o;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < size; i++) {
sb.append(queue[i] + ",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("]");
return sb.toString();
}
}
测试类:
package date;
public class MyQueueTest {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.add("2");
myQueue.add("3");
//查看队列第一个与元素
System.out.println(myQueue.peek());
//返回队列第一个元素 并离开队列
System.out.println(myQueue.poll());
//打印队列
System.out.println(myQueue);
}
/*
队列头元素2
删除队列第一个元素2
[3]
*/
}