Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,166 questions

40,722 answers

573 users

How to reverse the first N elements of LinkedList queue in Java

Booking.com | Official site | The best hotels, flights, car rentals & accommodations


73 views
asked Apr 15, 2020 by avibootz
edited Apr 16, 2020 by avibootz

1 Answer

0 votes
import java.util.LinkedList; 
import java.util.Stack; 
import java.util.Queue; 

public class MyClass {
    static Queue<Integer> queue; 
    
    static void reverseQueueFirstNElements(int n) { 
        if (queue.isEmpty() == true || n > queue.size() || n <= 0) 
            return; 

        Stack<Integer> stack = new Stack<Integer>(); 
  
        for (int i = 0; i < n; i++) { 
            stack.push(queue.peek()); 
            queue.remove(); 
        } 
  
        while (!stack.empty()) { 
            queue.add(stack.peek()); 
            stack.pop(); 
        } 
  
        for (int i = 0; i < queue.size() - n; i++) { 
            queue.add(queue.peek()); 
            queue.remove(); 
        } 
    } 

    public static void main(String args[]) { 
        queue = new LinkedList<Integer>(); 
        
        for (int i = 0; i < 10; i++) 
            queue.add(i); 
        
        System.out.println(queue); 
        
        reverseQueueFirstNElements(5);
        
        System.out.println(queue); 
    }
}



/*
run:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[4, 3, 2, 1, 0, 5, 6, 7, 8, 9]

*/

 





answered Apr 15, 2020 by avibootz

Related questions

1 answer 65 views
1 answer 81 views
1 answer 65 views
1 answer 225 views
1 answer 66 views
...