队列:进入的时候,从尾部进入,出去的时候,从头部离开的数据结构。队列是一种先入先出的数据结构,顾名思义,就像做核算检测时候的排队:
①先看第一种实现:链表实现队列
/**
* @author 25043
*/
public class MyQueue {
static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode head;
public ListNode tail;
public int usedSize;
/**
* 入队列,从尾部插入:入从尾入,出从头出
* 进入的值@param val
*/
public void offer(int val) {
ListNode listNode = new ListNode(val);
if (head == null) {
head = listNode;
tail = listNode;
} else {
tail.next = listNode;
tail = tail.next;
}
usedSize++;
}
/**
* 出队列
* 出出去的值@return
*/
public int poll() {
if (head == null) {
return -1;
}
int ret = head.val;
head = head.next;
if (head == null) {
tail = null;
}
usedSize--;
return ret;
}
/**
* 查看头的值
* 返回头的值@return
*/
public int peek() {
if (head == null) {
return -1;
}
return head.val;
}
/**
* 队列是否为空
* 布尔值@return
*/
public boolean isEmpty() {
return usedSize == 0;
}
/**
* 队列的长度
* 长度@return
*/
public int getUsedSize() {
return usedSize;
}
}
②环形队列(数组实现)
/**
* 环形的队列
*
* @author 25043
*/
public class MyRoundedQueue {
/**
* 数组元素
*/
private int[] elem;
/**
* 队头
*/
public int front;
/**
* 队尾
*/
public int rear;
public MyRoundedQueue(int k) {
elem = new int[k+1];
}
/**
* 入队列(从尾部插入,因此需要修改尾部的引用)
* 插入队列的值@param value
* 是否成功@return
*/
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;
}
front=(front+1)%elem.length;
return true;
}
public int front() {
if(isEmpty()){
return -1;
}
return elem[front];
}
public int rear() {
if(isEmpty()){
return -1;
}
int index=rear==0?elem.length-1:rear-1;
return elem[index];
}
public boolean isEmpty() {
return rear==front;
}
public boolean isFull() {
return (rear+1)%elem.length==front;
}
}
③用栈实现队列
public class MyQueue2 {
private final Stack<Integer> stack1;
private final Stack<Integer> stack2;
public MyQueue2() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
/**
* 出栈
* 出的值@return
*/
public int pop() {
int pop = 0;
if (empty()) {
return -1;
}
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/**
* 查看队列的头元素
* 查看@return
*/
public int peek() {
int pop = 0;
if (empty()) {
return -1;
}
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
/**
* 如果两个栈是空的,那么队列就是空的
* 布尔值@return
*/
public boolean empty() {
return stack1.empty() && stack2.empty();
}
}