Quick actions

cmd+k|ctrl+k

Navigation

Languages

Implement Queue using Stacks

Snippet info

Language

Csharp

Visibility

public

Author

anna1.1

Created

2020-07-18T07:21:33Z

Updated

2020-07-18T07:21:33Z

using System;
using System.Collections.Generic;

class MainClass 
{
    public static void Main() 
    {
          MyQueue q = new MyQueue();
          q.Push(1);
          q.Push(2);
          //Console.WriteLine(q.Peek());
          //Console.WriteLine(q.Pop());
          //Console.WriteLine(q.Empty());
          
          //while (!q.Empty())
          //{ Console.Write($"{q.Pop()} --> "); }
    }
}
    
public class MyQueue 
{
    private Stack<int> queueStack;
    private Stack<int> helperStack;

    public MyQueue() 
    {
         queueStack = new Stack<int>();
         helperStack = new Stack<int>();
    }
    
    public void Push(int x) 
    {
        queueStack.Push(x); //push to front of queue - fifo
    }
    
    public int Pop() 
    {
        Peek(); //does all the organising
        return helperStack.Pop();
    }
    
    public int Peek() 
    {
        if (helperStack.Count != 0) { return helperStack.Peek(); }
        while(queueStack.Count != 0) { helperStack.Push(queueStack.Pop()); }
        return helperStack.Peek(); //need to peek at bottom of queue stack as that's the front of the queue
    }
    
    public bool Empty() 
    {
        return queueStack.Count == 0 && helperStack.Count == 0;
    }
}
INFO