Rhyme/Java自定义队列

本文介绍了一个简单的Java自定义队列实现,包括队列的基本操作如添加元素和弹出顶部元素等。该队列具备自动扩容功能,当队列满时会自动扩大容量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java自定义队列

package com.maple.myqueue;

import java.util.Arrays;

/**
 * the implements of my queue
 * @author RhymeChiang
 * @date 2017/12/04
 **/
public class MyQueue {
    /**
     * the size of currrnt
     */
    private int size;
    private int capacity=3;
    /**
     * the container
     */
    private int data[]=new int[capacity];
    /**
     * the first point
     */
    private int first;
    /**
     * the end point
     */
    private int end;

    /**
     * append a data into my queue
     * @param a
     */
    public void append(int a){
        data[size]=a;
        size++;
        // expand the capacity
        if(size==data.length-1){
            capacity=capacity*2;
            int newData[] = new int[capacity];
            for(int i = 0;i<size;i++){
                newData[i]=data[i];
            }
            data = newData;
        }
    }

    /**
     * pop up the top element of this queue
     * @return
     */
    public int popUp(){
        int top = data[0];
        for(int i=0;i<size;i++){
            data[i]=data[i+1];
        }
        size--;
        return top;
    }

    public int[] getData() {
        return data;
    }

    public void setData(int[] data) {
        this.data = data;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.append(1);
        queue.append(2);
        queue.append(3);
        queue.append(4);
        queue.append(5);
        System.out.println("pop ele: "+queue.popUp());
        System.out.print("the elements in the queue:");
        for(int i=0;i<queue.getSize();i++){
            System.out.print(queue.getData()[i]+" ");
        }
    }
}

测试结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值