1、概念
->队列是只允许在一端进行数据插入,在另一端进行数据删除的数据结构。
-> 队列的特点:先进先出
-> 入队列:从队尾插入元素
-> 出队列:从队头删除数据
2、队列的使用
在java中,Queue是一个接口,底层通过链表实现。
(1)构造一个空的队列
Queue<E> queue = new LinkedList<>();
(2)入队
queue.offer(1);
(3)出队
queue.poll();
(4)获取队头元素
System.out.println(queue.peek());
(5)判断队列是否为空
queue.isEmpty()
3、 队列的模拟实现
4、循环队列
class MyCircularQueue {
//选用浪费一个空间的方法来实现一个循环队列
public int[] elem;
public int usedSize;
public int front;//队头
public int rear;//队尾
//构造器,设置队列长度为 k
public MyCircularQueue(int k) {
this.elem = new int[k+1];
}
//入队
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 front==rear;
}
public boolean isFull() {
if ((rear+1)%elem.length ==front){
//满了
return true;
}
return false;
}
}
5、练习
(1)用队列实现栈
class MyStack {
//要用两个队列来实现
Queue<Integer> q1 ;
Queue<Integer> q2 ;
int usedSize;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
//入栈
public void push(int x) {
if(!q1.isEmpty()){
q1.offer(x);
}else if(!q2.isEmpty()){
q2.offer(x);
}else{
q1.offer(x);
}
usedSize++;
}
//出栈
public int pop() {
if(empty()){
return -1;
}
if(!q1.isEmpty()){
int size = q1.size();
for(int i = 0; i < size-1; i++){
q2.offer(q1.poll());
}
usedSize--;
return q1.poll();
}else{
int size = q2.size();
for(int i = 0; i < size-1; i++){
q1.offer(q2.poll());
}
usedSize--;
return q2.poll();
}
}
public int top() {
if(empty()){
return -1;
}
if(!q1.isEmpty()){
int size = q1.size();
int cur = -1;
for(int i = 0; i < size; i++){
cur = q1.poll();
q2.offer(cur);
}
return cur;
}else{
int size = q2.size();
int cur = -1;
for(int i = 0; i < size; i++){
cur = q2.poll();
q1.offer(cur);
}
return cur;
}
}
public boolean empty() {
return usedSize == 0;
}
}
(2)用栈实现队列
class MyQueue {
//用两个栈来实现队列
Stack<Integer> s1 ; //专门用来实现入队的
Stack<Integer> s2 ; //专门用来实现出队的
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
//入队
public void push(int x) {
s1.push(x);
}
//出队
public int pop() {
if(empty()){
return -1;
}
if(s2.empty()){
while(!s1.empty()){
s2.push(s1.pop());
}
}
return s2.pop();
}
public int peek() {
if(empty()){
return -1;
}
if(s2.empty()){
while(!s1.empty()){
s2.push(s1.pop());
}
}
return s2.peek();
}
public boolean empty() {
return s1.empty() && s2.empty();
}
}