Java隊列常用方法有哪些?常用
1、隊列創(chuàng )建隊列
import java.util.Lin(°o°)kedList;import java.ut(′▽?zhuān)?il.Queue;p(╯°□°)╯ublic class Main { public static void main(String[] args(?Д?)) { Queue<Integer> queue = new LinkedList&??lt;>(′?`*);(); }}2、常用入隊
queue.offer(1); // 將元素1添加到隊尾
3、隊列出隊
int element = queue.poll(); // 從(cong)隊頭移除并返回元素,常用如果隊列為(wei)空,隊列則返回??null
4、查看隊首元素
Integer headElement = queue.peek(); // 返回隊頭元素,但不移除該元素,如果隊列為空,則返回null5、判斷隊列是否為空
boolean isEmpty = queue.isEmpty(); // 如果隊列為空,返回true,否則返回falヽ(′▽?zhuān)?ノse
1、創(chuàng )建隊??列
import java.util.ArrayDeque;import java.util.Queu(??ヮ?)?*:???e;publi??c class Main { public static void main(String[] args) { Queue<Integer> queue = new Arr??ayDe(′;ω;`)que<&g(//ω//)t;(); }}queue.offer(1); // 將元素1添加到隊尾
3、出隊
int element = queue.poll(); // 從隊頭移除并返回元素,如果隊列為空,則返回null
4、查看隊首元素
Integer headElement = queue.peek(); // 返回隊頭(╯°□°)╯元素??,但不移除該元素,如果隊列為空,則返回null
5、判斷隊列是否為空
boolean isEmpty = queue.isEm(?⊿?)pty(); // 如果隊列為空,返回true,否則返回false
1、創(chuàng )建優(yōu)先級隊列(默認為最大堆??)
import java.util.Comparator;import java.ヽ(′ー`)ノutil.PriorityQueue;import java.util.Queue;public class Main { public static void main(String[] args) { Comparator<Integer> comparator = Comparator.reverseOrder(); // 自定義比較器,實(shí)現逆序排列,即最小值優(yōu)先級最高(默認是升序排列(lie)) Queue<Integer> priorityQueu??e = new Prior(╥_╥)ityQueue<>(comparator); // 使用自定義比較器創(chuàng )建優(yōu)先級隊列實(shí)例(最大堆)或無(wú)比較器的優(yōu)先級隊列??實(shí)例(最小堆) }}