队列Queue

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表。


入队列(Enqueue):进行插入操作的一端称为队尾

出队列(Dequeue):进行删除操作的一端称为队头

队列具有先进先出的特性



大家可以简单理解为日常生活中“排队”这一现象。


队列的模拟实现

简单想一想,因为LinkedList实现了Queue接口,所以Queue的底层是由链表实现的。


受到LinkedList的影响,我们下意识认为Queue的底层是双向链表,那单链表能不能来实现队列呢?


那么以LinkedList来实现队列怎么样呢?

建立内部类


//内部类

   public static class ListNode {

       public ListNode prev;

       public ListNode next;

       int value;


       ListNode(int value){

           this.value=value;

       }

   }


   public ListNode first=null;

   public ListNode last=null;

   int Usedsize=0;


入队列—向双向链表位置插入新节点


public void offer(int val){

       ListNode node=new ListNode(val);

       if(first==null){

           first=last=node;

       }else{

           last.next=node;

           node.prev=last;

       }

       last=node;

       Usedsize++;

   }


出队列—将双向链表第一个节点删除掉


public int poll(){

       int val=0;

       if(first==null){

           return 0;

       }

       if(first==last){

           last=null;

           first=null;

       }else{

           val=first.value;

           first=first.next;

           first.prev.next=null;

           first.prev=null;

       }

       Usedsize--;

       return val;

   }


获取队头元素—获取链表中第一个节点的值域


public int peek(){

       if(first==null){

           return 0;

       }

       return first.value;

   }

class MyCircularQueue {

    public int front;
    public int rear;
    public int[] elem;

    public MyCircularQueue(int k) {
        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 rear==front;
    }
    
    public boolean isFull() {
        return (rear+1)%elem.length==front;
    }
}