队列:
概念:只允许在一端进行插入数据操作(队尾rear),再另一端进行删除(队头front)
实现:数组;链表(头插,尾删)
特性:先进先出
入队列:offer(e) 出队列:poll() 队首元素:peek()
假溢出:
不可以添加元素,否组会造成数组越界
此时又不应该扩充数组,因为还有大量实际空间并未使用
空:front=rear
满:front=(rear+1)%size
进队:rear=(rear+1)%size
出队:front=(front+1)%size
解决假溢出:循环队列
数组实现
如何区满与空;
空的循环队列:front=rear
满的循环队列:(rear+1)%size=front
队列长度:(rear-front+size)%size
进队:rear=(rear+1)%size;
出队:front=(front+1)%size;
双端队列:Deque
两端都可以进行插入和删除操作
public class MyQueue {
public static void main(String[] args) {
Queue queue=new Queue();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.display();
System.out.println();
queue.poll();
queue.display();
}
}
class Queue{
Node front;
Node rear;
int size;
//插入队列
public void offer(int data){
Node node=new Node(data);
if(rear==null){
front=node;
rear=node;
}else{
rear.next=node;
rear=rear.next;
}
size++;
}
//出队列
public int poll(){
if(front==null){
throw new RuntimeException("运行时出错");
}
int data=front.data;
front=front.next;
return data;
}
//队首元素
public int peek(){
return front.data;
}
public void display(){
Node cur=front;
while(cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
}
public boolean empty(){
return size==0;
}
}
class Node{
int data;
Node next;
Node(int data){
this.data=data;
next=null;
}
}