YogenGhodke
6/26/2019 - 1:21 AM

Queue in Java

import java.util.LinkedList;
import java.util.Queue;

main()
{
    Queue<Integer> q = new LinkedList<>();
    
    // Adds elements {0, 1, 2, 3, 4} to queue 
    for (int i=0; i<5; i++) 
     q.add(i);
     
    // Display contents of the queue. 
    System.out.println("Elements of queue-"+q); 
    
    // To remove the head of queue. 
    q.remove(); 
    
    // To view the head of queue 
    int head = q.peek();
    
    int size = q.size();
    
    //Iterate All Elements in Queue
    Iterator it = q.iterator();
        while(it.hasNext())
            System.out.println(it.next());
        
    //Code to Print the nth element of the Queue 
      int flag = 0;
        for(flag=0;flag<=n;flag++)
        {
            Integer x = (Integer) it.next();
            if(flag==n)
                System.out.println(x);

        }    
    
    // LL to Array Conversion
    
    Object[] p = q.toArray();
    System.out.println(p[3]);
    
}