...
/Solution Review: Reversing First "k" Elements of Queue
Solution Review: Reversing First "k" Elements of Queue
This review provides a detailed analysis to help you solve the "Reversing First "k" Elements of Queue" challenge.
We'll cover the following...
Solution: Using a queue #
Press + to interact
main.cs
DoublyLinkedList.cs
Queue.cs
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 queueif (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:
-
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()
- Constructor: