java语言 循环数组实现队列

使用了循环数组实现的,所以时间复杂度和空间复杂度都是O(1)

队列实现类长这样

package NodeTest;

/**
 * @ClassName MyQuque
 * @Description TODO
 * @Author 14784
 * @Date 2020/6/21 21:55
 * @Version 1.0
 */
public class MyQuque {
    private int array[];   //存放队列的循环数组
    private int front;     //队头下标
    private int rear;      //队尾下标


    public MyQuque(int capcacity) {
        this.array = new int[capcacity];
    }

    /**
     * 入队
     * @param element 入队元素
     * @throws Exception
     */
    public void enQueue(int element) throws Exception{
        if ((rear+1)%array.length==front){
            throw new Exception("队列已满!");
        }
        array[rear] = element;
        rear = (rear+1)%array.length;   //小数取模大数得本身
    }

    /**
     * 出队
     * @return dequeeuElement 出队元素
     * @throws Exception
     */
    public int deQueue () throws Exception{
        if (rear == front){
         throw new Exception("队列为空!");
        }
        int dequeueElement = array[front];   //取出元素
        front = (front+1)%array.length;      //对头位置改变

        return dequeueElement;
    }

    /**
     * 输出队列
     */
    public void output(){
        for (int i = front ;i!=rear;i = (i+1)% array.length){
            System.out.print(array[i]+",");
        }
        System.out.println();
    }

}

main方法:

package NodeTest;



/**
 * @ClassName main
 * @Author 14784
 * @Date 2020/6/3 17:38
 * @Version 1.0
 */
public class main {
    public static void main(String[] args) throws Exception{
        /**
         * 队列
         */
        MyQuque myQuque = new MyQuque(6);
        System.out.println("入队元素为");
        myQuque.enQueue(3);
        myQuque.enQueue(5);
        myQuque.enQueue(6);
        myQuque.enQueue(8);
        myQuque.enQueue(1);
        myQuque.output();
        System.out.println("出队后");
        myQuque.deQueue();
        myQuque.deQueue();
        myQuque.deQueue();
        myQuque.output();
        System.out.println("重新入队新元素");
        myQuque.enQueue(2);
        myQuque.enQueue(4);
        myQuque.enQueue(9);
        myQuque.output();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值