Java有关队列的基本操作

打印 上一主题 下一主题

主题 891|帖子 891|积分 2673

什么是队列?

队列是一种线性数据结构,队列中的元素只能先进先出;
队列的出口端叫做队头,入口端叫做队尾。


队列的基本操作

1.入队:

    1.      只允许在队尾的位置放入元素,新元素的下一个位置将会成为新的队尾;
    复制代码
  1. public void enQueue(int element) throws Exception{
  2.         if((rear+1)%array.length==front){
  3.             throw new Exception("队满!!!");
  4.         }
  5.         array[rear]=element;
  6.         rear=(rear+1)%array.length;
  7.     }
复制代码
2.出队:

    1.      类似于入队,只允许在对头的位置移除元素,出队元素的后一个元素将会成为新的对头;
    复制代码
    1.      当一个队列经过反复的入队和出队操作,还剩下2个元素,这时又有新元素入队时,在数组不扩容的
    复制代码
    1.      情况下,将队尾指针重新指向数组的首位,实现循环队列的数据结构。
    复制代码
  1. public int deQueue() throws Exception{
  2.         if(front==rear){
  3.             throw new Exception("队满!!!");
  4.         }
  5.         int deElement=array[front];
  6.         front=(front+1)%array.length;
  7.         return deElement;
  8.     }
复制代码
3.判断队满的情况:

    1.      当(队尾下标+1)%数组长度=队头下标时,队满;
    复制代码
    1.      队尾指针指向的位置永远空出一位,所以队列最大容量比数组长度小1。
    复制代码
完整代码

点击查看代码
  1. package Queue;public class MyQueue {    //定义数组    private int[] array;    //对头指针    private int front;    //队尾指针    private int rear;    //定义队列的构造方法(类似数组)    public MyQueue(int capacity){        this.array=new int[capacity];    }    //入队操作(element:入队元素)    public void enQueue(int element) throws Exception{
  2.         if((rear+1)%array.length==front){
  3.             throw new Exception("队满!!!");
  4.         }
  5.         array[rear]=element;
  6.         rear=(rear+1)%array.length;
  7.     }    //出队操作    public int deQueue() throws Exception{
  8.         if(front==rear){
  9.             throw new Exception("队满!!!");
  10.         }
  11.         int deElement=array[front];
  12.         front=(front+1)%array.length;
  13.         return deElement;
  14.     }    //输出队列    public void output(){        for(int i=front;i!=rear;i=(i+1)%array.length){            System.out.print(array[i]+" ");        }    }    public static void main(String[] args) throws Exception{        MyQueue myQueue=new MyQueue(6);        myQueue.enQueue(1);        myQueue.enQueue(2);        myQueue.enQueue(3);        myQueue.enQueue(4);        myQueue.enQueue(5);        myQueue.deQueue();        myQueue.deQueue();        myQueue.enQueue(6);        myQueue.enQueue(7);        myQueue.output();    }}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

万有斥力

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表