1. 队列
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)。
入队列:进行插入操作的一端称为队尾(Tail/ Rear)。
出队列:进行删除操作的一端称为队头(Head/ Front)。
2. Java中的组织关系
创建队列
LinkedList 实现了 Queue 接口。
Queue<String> queue = new LinkedList<>();
3. 实现自己的队列Queue - MyQueue
public class Node {
int val;
Node next;
Node(int val, Node next){
this.val = val;
this.next = next;
}
Node(int val){
this(val, null);
}
}
public class MyQueue {
private Node head = null;
private Node tail = null;
private int size = 0;
public void offer(int v){
Node node = new Node(v);
if (tail == null){
head = node;
}else {
tail.next = node;
}
tail = node;
size++;
}
public int poll(){
if (size == 0){
throw new ArrayIndexOutOfBoundsException();
}
if (size == 1){
head = tail = null;
size = 0;
return head.val;
}else {
Node deleteNode = head;
head = head.next;
size--;
return deleteNode.val;
}
}
public int peek(){
if (size == 0){
throw new ArrayIndexOutOfBoundsException();
}
return head.val;
}
public boolean isEmpty(){
return size == 0;
}
public int size(){
return size;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
for (Node cur = head; cur != null; cur = cur.next){
stringBuilder.append(cur.val);
if (cur.next != null){
stringBuilder.append(",");
}
}
stringBuilder.append("]");
return stringBuilder.toString();
}
}