特殊的线性表,插入在队尾,删除的是对头。
先进先出。
一:队列
1.普通队列实现
package com.jun.algorithm.foundation.main; /** * 使用数组实现队列 * * @author caojun */ public class ArrayQueue { private int[] data; // 对头的位置 private int head = 0; // 队尾的位置 private int tail = 0; // 队列长度 private int n = 0; ArrayQueue(int cap) { data = new int[cap]; n = cap; } public void push(int num) { // 如果没有空间了,移动一次 if (tail == n) { return; } data[tail] = num; tail++; } public int pop() { if (isEmpty()) { return -1; } int m = data[head]; head++; return m; } public boolean isEmpty() { return head == tail; } }
2.循环队列实现
package com.jun.algorithm.foundation.main; /** * 使用数组实现循环队列 * * @author caojun */ public class CircleArrayQueue { private int[] data; // 对头的位置 private int head = 0; // 队尾的位置 private int tail = 0; // 队列长度 private int n = 0; CircleArrayQueue(int cap) { data = new int[cap]; n = cap; } public void push(int num) { // 满了的判断条件 if ((tail + 1) % n == head) { return; } data[tail] = num; tail = (tail + 1) % n; } public int pop() { if (isEmpty()) { return -1; } int m = data[head]; head = (head + 1) % n; return m; } public boolean isEmpty() { return head == tail; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)