数据结构(3)——队列结构(java实现队列结构)

队列结构

队列结构是按照 “先进先出 ”(First In First Out,FIFO)的原则处理数据的。在队列结构中,允许对两端进行操作,但是在两端的操作不同。在表的一端可以进行删除操作,称为队头;在表的另一端只能进行插入操作,称为队尾。如果队列中没有数据元素,则称为空队列。

  • 入队列:将一个元素添加到队尾(相当于到队列最后排队等候)。
  • 出队列:将队头的元素取出,同时删除该元素,使后一个元素成为队头。
public class Queue {

    private int [] queArray;
    private int maxSize;
    public  int front;
    public int tail;
    private int length;
    //构造方法初始化队列
    public Queue(int maxSize){
        this.maxSize = maxSize;
        queArray = new int[maxSize];
        front = 0;
        tail = -1;
        length = 0;
    }
    //判断空队列
    public boolean isEmpty(){
        return (length == 0);
    }
    //判断满队列
    public boolean isFull(){
        return (length == maxSize);
    }
    //插入
    public void insert(int elem) throws Exception {
        if (isFull()){
            throw new Exception("队列已满,不能进行插入操作");
        }else{
            //如果队尾指针已达到数组的末端,插入到数组的第一个位置
            if(tail == maxSize-1){
                tail = -1;
            }
            queArray[++tail] = elem;
            length++;
        }

    }
    //移除
    public int remove() throws Exception {
        if (isEmpty()){
            throw new Exception("队列为空,移除失败");
        }
        int elem = queArray[front++];
        //如果队头指针已到达数组末端,则移到数组第一个位置
        if(front == maxSize){
            front =0;
        }
        length--;
        return elem;
    }
    //查看队头元素
    public int peek() throws Exception {
        if (isEmpty()){
            throw new Exception("队列内没有元素!");
        }
        return queArray[front];
    }
    //获取队列长度
    public int size(){
        return length;
    }
    //释放队列
    public void freeQueue(){
        if (queArray != null){
            queArray = null;
        }
    }

//测试
    public static void main(String[] args) throws Exception {
        Queue queue = new Queue(5);
        System.out.println("入队列操作:");
        Scanner scanner = new Scanner(System.in);
        int i;
        do {
            if ((i=scanner.nextInt())==0){
                break;
            }else{
                queue.insert(i);
            }
        }while(true);
        String temp = "1";
        System.out.println(queue.isFull());
        System.out.println("出队列操作:");
        temp = scanner.next();
        while(!temp.equals("0")){
            System.out.println(queue.remove());
            temp = scanner.next();
        }
        System.out.println("测试结束");
        queue.freeQueue();

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值