- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements