Create a queue using LinkedList class in Java


To create a queue using LinkedList class, try the following −

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");

After that to print the elements, you need to use check a condition for Queue as shown below −

Object ob;
while ((ob = q.poll()) != null) {
   System.out.println(ob);
}

The following is an example −

Example

 Live Demo

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("
Queue elements...");     Object ob;       while ((ob = q.poll()) != null) {          System.out.println(ob);       }    } }

Output

Queue head = abc
Size = 8
Queue elements...
abc
def
ghi
jkl
mno
pqr
stu
vwx

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements