队列

队列:

概念:只允许在一端进行插入数据操作(队尾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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值