队列入队出队

package Queue;

public class MyQueue {
int[] array=new int[6];
//队头
private int fornt;
//队尾
private int last;

public static void main(String[] args) throws Exception {

    MyQueue myQueue=new MyQueue();
    //入队
    myQueue.enQueue(1);
    myQueue.enQueue(2);
    myQueue.enQueue(3);
    //输出队列
    myQueue.putQueue();
    //出队
    myQueue.outQueue();
    System.out.println("出队后");
    //输出队列
    myQueue.putQueue();
}

private void putQueue() {
    for (int i = fornt; i!=last ; i=(i+1)%array.length) {
        System.out.println(array[i]);
    }
}


private void enQueue(int element) throws Exception {
//(队尾下标+1)/数组长度 =队头下标
    if ((last+1)%array.length ==fornt){
        throw new Exception("队列已满");
    }
    array[last]=element;
    //队尾
    last=(last+1)%array.length;
}
private int outQueue() throws Exception {
    if ((last+1)%array.length ==fornt){
        throw new Exception("队列已满");
    }
    int deQueueElement=array[fornt];
    fornt=(fornt+1)%array.length;
    return deQueueElement;
}

}

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容