队列--数据结构和算法笔记

队列

1.队列是一个有序列表,可以用数组或链表来实现

2.遵循先入先出的原则(先存入队列的数据要先取出,后存入的后取出)

数组模拟队列:

import java.util.Scanner;

public class www {
    public static void main(String[] args) {
        ww w = new ww(3);
        Scanner s = new Scanner(System.in);
        boolean loop = true;
        while (loop) {
            System.out.println("1.添加");
            System.out.println("2.取出");
            System.out.println("3.展示");
            System.out.println("4.退出");
            switch (s.next()) {
                case "1":
                    try {
                        System.out.println("输入一个数字");
                        w.add(s.nextInt());

                    } catch (Exception e) {
                        // TODO: handle exception
                        System.out.println(e.getMessage());
                    }

                    break;

                case "2":
                    try {
                        System.out.println(w.get());

                    } catch (Exception e) {
                        // TODO: handle exception
                        System.out.println(e.getMessage());
                    }
                    break;
                case "3":
                    w.show();
                    break;
                case "4":
                    s.close();
                    loop = false;
                    break;
            }
        }
    }
}

class ww {
    private int i[];// 数组
    private int front;// 后端下标
    private int rear;// 前端下标
    private int max;// 数组大小

    public ww(int max) {
        this.max = max;
        i = new int[max];
    }
    // 判断是否为空
    private boolean isnull() {
        return front == rear;
    }
    // 判断是否为满
    private boolean isfull() {
        return front - rear == max;
    }
    // 添加
    public void add(int n) {
        if (isfull()) {
            throw new RuntimeException("队列满,添加失败");
        }
        System.err.println(front);
        i[front++ % max] = n;
    }
    // 取出数据
    public int get() {
        if (isnull()) {
            throw new RuntimeException("队列空,取出失败");
        }
        System.out.println(rear);
        return i[rear++ % max];
    }
    // 遍历数组
    public void show() {
        for (int j = rear; j < front; j++) {

            System.out.println("i[" + j % max + "]" + i[j % max]);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值