目录
1.概念
2.常用的队列方法
2.1 方法
方法 | 功能 |
---|---|
offer() | 入队列 |
poll() | 出队列,队列为空,抛出NoSuchElementException异常 |
peek() | 获得队头元素,抛出NoSuchElementException异常 |
size() | 获得队列元素个数 |
isEmpty() | 检测队列是否为空 |
2.2 代码
public static void main(String[] args) {
Queue<Character> queue = new LinkedList<>();
queue.offer('A');//A
queue.offer('B');//B A
queue.offer('C');//C B A
System.out.println(queue.poll());//A
System.out.println(queue.peek());//B
System.out.println(queue.poll());//B
queue.offer('D');//D C
System.out.println(queue.size());//2
System.out.println(queue.isEmpty());//fasle
}
注意:
队列操作的poll(),peek()的执行条件是队列不为空。
3.自己实现队列
3.1 构造MyQueue
public class MyQueue {
public int val;
public MyQueue next;
public MyQueue prev;
public MyQueue first;//队头
public MyQueue last;//队尾
public int size;//元素个数
public MyQueue(){}
public MyQueue(int val){
this.val = val;
}
}
3.2 入队列offer()
//入队列
public void offer(int val){
MyQueue myQueue = new MyQueue(val);
if(size == 0){
first = myQueue;
last = myQueue;
size++;
return;
}
last.next = myQueue;
myQueue.prev = last;
last = last.next;
size++;
}
3.3 出队列poll()
//出队列
public int poll(){
if(first == null){
throw new NoSuchElementException();
}
MyQueue myQueue = first;
if(first == last){
last = null;
first = null;
}else {
first = first.next;
first.prev = null;
}
size--;
return myQueue.val;
}
3.4 获得队头peek()
//获得队头元素
public int peek(){
if(first == null){
throw new NoSuchElementException();
}
return first.val;
}
3.5 是否为空isEmpty()
//是否为空队列
public boolean isEmpty(){
return size == 0;
}
3.6 获得队列大小size()
//队列元素个数
public int getSize(){
return size;
}
4.循环队列
4.1 概念
4.2 解析
4.3 如何判断队列满
4.4 代码(保留一个位置实现)
class MyCircularQueue {
private int[] elem;
private int rear;
private int frond;
public MyCircularQueue(int k) {
this.elem = new int[k];
}
public boolean enQueue(int value) {
if(isFull()){
return false;
}
elem[rear] = value;
rear = (rear + 1) % elem.length;
return true;
}
public boolean deQueue() {
if(isEmpty()){
return false;
}
frond = (frond + 1) % elem.length;
return true;
}
public int Front() {
if(isEmpty()){
return -1;
}
return elem[frond];
}
public int Rear() {
if(isEmpty()){
return -1;
}
return elem[rear];
}
public boolean isEmpty() {
return frond == rear;
}
public boolean isFull() {
return (rear + 1) % elem.length == frond;
}
}