1 Star 1 Fork 1

xcc/structures-and-algorithm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
SingleQueueDemo.java 3.29 KB
一键复制 编辑 原始数据 按行查看 历史
xcc 提交于 2020-12-14 20:34 +08:00 . 修改包名
package com.xcc.dataStructures.demo02_queue;
import java.util.Scanner;
/**
* 简单队列
*
* @author xiaocheng
* @date 2020/11/16 18:27
*/
public class SingleQueueDemo {
public static void main(String[] args) {
System.out.println("========简单队列测试========");
ArrayQueue queue = new ArrayQueue(3);
while (true) {
System.out.println();
System.out.println("s[show]:遍历链表");
System.out.println("h[head]:查看头元素");
System.out.println("a[add]:添加元素");
System.out.println("g[get]:获取元素");
System.out.println("e[exit]:退出");
System.out.print("请输入方法:");
Scanner scanner = new Scanner(System.in);
String key = scanner.next();
switch (key) {
case "a":
try {
System.out.print("请输入添加的值:");
int num = scanner.nextInt();
queue.add(num);
} catch (Exception e) {
System.err.println(e.getMessage());
}
break;
case "g":
try {
System.out.printf("获取的元素为: %d \n", queue.get());
} catch (Exception e) {
System.err.println(e.getMessage());
}
break;
case "s":
queue.show();
break;
case "h":
System.out.println(queue.head());
break;
case "e":
return;
}
}
}
}
/**
* 数组队列
*/
class ArrayQueue {
private int maxSize;
private int rear;
private int front;
private int[] arr;
/**
* 数组初始化
*/
public ArrayQueue(int maxSize) {
this.maxSize = maxSize; //定义数据的长度
arr = new int[maxSize]; //初始化数组
rear = -1; //定义尾部元素的指针
front = -1; //定义数组的第一个元素的前一个元素
}
/**
* 获取头元素
*/
public int head() {
return arr[front + 1];
}
/**
* 往队列中添加元素
*/
public void add(int num) {
//如果队列为满
if (isFull()) {
throw new RuntimeException("队列满,不能再添加!!!");
}
rear++; //当前元素上移
arr[rear] = num;
}
/**
* 从队列中获取元素
*/
public int get() {
if (isEmpty()) {
throw new RuntimeException("队列空,不能再获取!!!");
}
front++;
return arr[front];
}
/**
* 遍历队列
*/
public void show() {
if (isEmpty()) {
System.out.println("[]");
}
for (int i = front+1; i < rear+1; i++) {
System.out.printf("arr[%d] = %d\n", i, arr[i]);
}
}
/**
* 判断队列是否为空
*/
public boolean isEmpty() {
return rear == front;
}
/**
* 判断队列是否满
*/
public boolean isFull() {
return rear == maxSize - 1;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/xiaocheng0902/structures-and-algorithm.git
git@gitee.com:xiaocheng0902/structures-and-algorithm.git
xiaocheng0902
structures-and-algorithm
structures-and-algorithm
master

搜索帮助