Search⌘ K
AI Features

Solution Review: Reversing First "k" Elements of Queue

Explore how to reverse the first k elements of a queue by utilizing stack and queue operations. Understand the implementation details of enqueue, dequeue, push, and pop functions, and grasp the algorithm's logic and time complexity.

We'll cover the following...

Solution: Using a queue #

C#
using System;
using System.Collections;
namespace chapter_4
{
class Challenge_3
{
static Queue reverseK(Queue queue, int k)
{
//1.Push first k elements in queue in a stack.
//2.Pop Stack elements and enqueue them at the end of queue
//3.Dequeue queue elements till "k" and append them at the end of queue
if (queue.Count != 0)
{
Stack stack = new Stack();
int count = 0;
while (count < k)
{
stack.Push(queue.Dequeue());
count++;
}
while (stack.Count != 0)
{
queue.Enqueue(stack.Pop());
}
int size = queue.Count;
for (int i = 0; i < size - k; i++)
{
queue.Enqueue(queue.Dequeue());
}
}
return queue;
}
static void Showqueue(Queue s)
{
Console.WriteLine("The queue is: ");
while (s.Count != 0)
{
Console.Write('\t' + s.Peek().ToString());
s.Dequeue();
}
Console.WriteLine('\n');
}
static void Main(string[] args)
{
Queue mQ = new Queue();
mQ.Enqueue(1);
mQ.Enqueue(2);
mQ.Enqueue(3);
mQ.Enqueue(4);
mQ.Enqueue(5);
mQ = reverseK(mQ, 5);
Showqueue(mQ);
return ;
}
}
}

Take a look at the algorithm step-by-step:

  1. Check if the queue is empty (line 14). If it is not, start by creating a stack. The available stack functions are:

    • Constructor: myStack()
    • Push elements: push(int) to add elements to the stack
    • Pop elements: pop() to remove or pop the top element from the stack.
    • Check if empty: isEmpty() returns true if the stack is empty and false otherwise.
    • Return top: getTop() function returns the top element (that has been added at the end) without removing it from the stack.
  2. The function reverseK(queue, k) takes ...