...

/

Solution Review: Implement a Queue Using Stacks

Solution Review: Implement a Queue Using Stacks

This review provides a detailed analysis of the different ways to solve the "Implement a Queue Using Stacks" challenge.

Solution #1: Two stacks working in enqueue()

Press + to interact
using System;
using System.Collections.Generic;
namespace chapter_4
{
//Create Stack => myStack stack = new myStack(5);
//where 5 is size of stack
//Push Function => stack.push(int);
//Pop Function => stack.pop();
//TopFunction => stack.getTop();
//Helper Functions => stack.isEmpty();
class newQueue
{
Stack <int> mainStack;
Stack <int> tempStack;
public newQueue()
{
//Can use size from argument to create stack
mainStack = new Stack<int> ();
tempStack = new Stack<int> ();
}
void EnQueue(int value)
{
//Traverse elements from mainStack to tempStack
//Push given value to mainStack
//Traverse back the elements from tempStack to mainStack
while (mainStack.Count != 0)
{
tempStack.Push(mainStack.Pop());
}
mainStack.Push(value);
while (tempStack.Count != 0)
{
mainStack.Push(tempStack.Pop());
}
}
int DeQueue()
{
//If mainStack is empty then we have no elements.
//else return top element of mainStack as we always put oldest entered
//element at the top of mainStack
if (mainStack.Count == 0)
return -1;
else
return mainStack.Pop();
}
static void Main(string[] args)
{
newQueue queue = new newQueue();
queue.EnQueue(1);
queue.EnQueue(2);
queue.EnQueue(3);
queue.EnQueue(4);
queue.EnQueue(5);
Console.WriteLine( queue.DeQueue());
Console.WriteLine( queue.DeQueue());
Console.WriteLine( queue.DeQueue());
Console.WriteLine(queue.DeQueue());
Console.WriteLine( queue.DeQueue());
Console.WriteLine(queue.DeQueue());
return ;
}
};
}

In this approach, use two stacks. The mainStack stores the queue elements while the tempStack acts as a temporary buffer to provide queue functionality.

Make sure that after every enqueue operation, the newly inserted value is at the bottom of the main stack. Before insertion, all the other elements are transferred to tempStack and ...