使用Java中的LinkedList类创建队列
要使用LinkedList类创建队列,请尝试以下操作-
Queue<String> q = new LinkedList<String>(); q.offer("abc"); q.offer("def"); q.offer("ghi"); q.offer("jkl"); q.offer("mno"); q.offer("pqr"); q.offer("stu"); q.offer("vwx");
之后打印元素,您需要使用检查队列的条件,如下所示-
Object ob; while ((ob = q.poll()) != null) { System.out.println(ob); }
以下是一个例子-
示例
import java.util.LinkedList; import java.util.Queue; public class Demo { public static void main(String[] args) { Queue<String> q = new LinkedList<String>(); q.offer("abc"); q.offer("def"); q.offer("ghi"); q.offer("jkl"); q.offer("mno"); q.offer("pqr"); q.offer("stu"); q.offer("vwx"); System.out.println("Queue head = " + q.element()); System.out.println("Size = " + q.size()); System.out.println("\nQueue elements..."); Object ob; while ((ob = q.poll()) != null) { System.out.println(ob); } } }
输出结果
Queue head = abc Size = 8 Queue elements... abc def ghi jkl mno pqr stu vwx