How to reverse the first N elements of a LinkedList queue in C#

1 Answer

0 votes
using System;
using System.Collections.Generic; 

class Program
{
    public static LinkedList<int> queue; 
  
    public static void reverseQueueFirstNElements(int n) { 
        if (queue.Count == 0 || n > queue.Count || n <= 0) { 
            return; 
        } 

        Stack<int> stack = new Stack<int>(); 
      
        for (int i = 0; i < n; i++) { 
            stack.Push(queue.First.Value); 
            queue.RemoveFirst(); 
        } 
      
        while (stack.Count > 0) { 
            queue.AddLast(stack.Peek()); 
            stack.Pop(); 
        } 
      
        for (int i = 0; i < queue.Count - n; i++) { 
            queue.AddLast(queue.First.Value); 
            queue.RemoveFirst(); 
        } 
    } 
  
    public static void PrintQueue() { 
       foreach(int n in queue) { 
            Console.Write("{0} ", n); 
        } 
    } 
    
    static void Main() {
        queue = new LinkedList<int>(); 
    
        queue.AddLast(5); 
        queue.AddLast(2); 
        queue.AddLast(7); 
        queue.AddLast(3); 
        queue.AddLast(6); 
        queue.AddLast(1); 
        queue.AddLast(9); 

        PrintQueue(); 
        
        reverseQueueFirstNElements(4); 
        
        Console.WriteLine();
        
        PrintQueue(); 
    }
}


/*
run:

5 2 7 3 6 1 9 
3 7 2 5 6 1 9 

*/

 



answered Apr 16, 2020 by avibootz

Related questions

1 answer 129 views
1 answer 146 views
1 answer 112 views
1 answer 279 views
1 answer 104 views
1 answer 116 views
1 answer 114 views
...