栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数组实现队列java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数组实现队列java

package day02;

import java.util.linkedList;
import java.util.Queue;
import java.util.Stack;

public class Suan04Queue02 {
    
    public static class MyQueue{
        public int[] arr;
        
        public int begin;
        public int end;
        public int size;
        public MyQueue(int limit){
            begin = 0;
            end = 0;
            size = 0;
            arr = new int[limit];
        }
        //判断队列是否满了,满了则不能插入
        public void push(int value){
            if(size==arr.length){
                throw new RuntimeException("队列满了不再加");
            }
            //没满则可插入,将队列长度+1
            size++;
            //入队
            arr[end] = value;
            //入队后将end位置下移,nextIndex的作用就是判断end是否到了数组的最后,若是到了则循环end=0
            end = nextIndex(end);
        }
        //出队是返回并删除数组的begin位置的数
        public int poll(){
            if(size == 0){
                throw new RuntimeException("队列空不能再减");
            }
            //队列长度减1
            size--;
            //同理
            int temp = arr[begin];
            begin = nextIndex(begin);
            return temp;
        }
        public int nextIndex(int end){
            if(end == arr.length){
                return 0;
            }
            return (end+1);
        }
        public static void main(String[] args) {
            int oneTestDataNum = 10;
            int value = 10;
            int testTimes = 10;
            for (int i = 0; i < testTimes; i++) {
                MyQueue myQueue = new MyQueue(100);
                Queue queue = new linkedList<>();
                for (int j = 0; j < oneTestDataNum; j++) {

                    int numq = (int) (Math.random() * value);
                    if (queue.isEmpty()) {
                        myQueue.push(numq);
                        queue.offer(numq);
                    } else {
                        if (Math.random() < 0.5) {
                            myQueue.push(numq);
                            queue.offer(numq);
                        } else {
                            if (myQueue.poll()!=queue.poll()) {
                                System.out.println("oops!");
                            }
                        }
                    }
                }
            }
            System.out.println("finish!");
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/324920.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号