模拟环形队列:数组基础,环形思想

本文详细介绍了使用Java实现循环数组的数据结构,包括初始化、判断空满状态、添加元素、显示首个元素及全部元素等核心功能。通过具体代码示例,展示了如何在循环数组中进行数据的增删查操作。
import java.util.Scanner;

public class CircleArray {
    public int Maxsize;
    public int front;
    public int end;
    public int[] array;
    public CircleArray(int maxsize){
        Maxsize=maxsize;
        array = new int[maxsize];
        front=0;
        end=0;
    }
    public boolean Isempty()

    {
        return front==end;
    }
    public boolean Isfull()
    {
        return (end+1)%Maxsize==front;
    }
    public void Addone(int n)
    {
        if (Isfull())
        {
            System.out.println("the array is full now!");
            return;
        }
            array[end]=n;
            end=(end+1)%Maxsize;


    }
    public void Showfirst()
    {
        if (Isempty())
        {
            throw new RuntimeException("the array is empty!");
        }else{
            System.out.printf("array[%d]=%d",front,array[front]);
            front=(front+1)%Maxsize;
        }
    }
    public void ShowAll()
    {
        for (int i = front; i <front+count(); i++) {
            System.out.printf("array[%d]=%d",i%Maxsize,array[i%Maxsize]);
            System.out.println();
        }
    }
    public int count()
    {
        return (end-front+Maxsize)%Maxsize;
    }
    

}
import java.util.Scanner;

public class demo {
    public static void main(String[] args) {
        boolean loop=true;
        CircleArray circleArray = new CircleArray(3);
        while (loop)
       {
           System.out.println("a(add one data)");
           System.out.println("g(show the first)");
           System.out.println("s(show all datas)");
           System.out.println("e(exit)");
           Scanner scanner = new Scanner(System.in);
           char key = scanner.next().charAt(0);
           switch (key)
           {
               case 'a':
                   System.out.println("enter one number:");
                   int anInt = scanner.nextInt();
                   circleArray.Addone(anInt);
                   break;
               case 'g':
                   circleArray.Showfirst();
                   break;
               case 's':
                   circleArray.ShowAll();
                   break;
               case 'e':
                   loop=false;
                   break;
               default:
                   break;
           }


       }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值