Implement Stack using Queue

Write a program to demonstrate stack Implementation using Queue.

Solution:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace StackOperation
{
    class Program
    {
        public static void Main()
        {
            var st = new Stack<int>();
            st.Push(1);
            st.Push(2);
            st.Push(5);
            st.Push(3);
            st.Push(4);

            Console.WriteLine("Stack:");
            foreach (var i in st)
                Console.WriteLine(i);

            Console.ReadLine();
        }

    }

    public class Stack<T> : IEnumerable<T>
    {
        public Queue Queue1 = new Queue();
        public Queue Queue2 = new Queue();
        public int QueueSize;

        public Stack()
        {
            QueueSize = 0;
        }

        public void Push(T x)
        {
            QueueSize++;
            Queue2.Enqueue(x);

            while (Queue1.Count > 0)
            {
                Queue2.Enqueue(Queue1.Peek());
                Queue1.Dequeue();
            }
 
            var q = Queue1;
            Queue1 = Queue2;
            Queue2 = q;
        }

        public void Pop()
        {
            if (Queue1.Count == 0)
                return;
            Queue1.Dequeue();
            QueueSize--;
        }

        public int Top()
        {
            if (Queue1.Count == 0)
                return -1;
            return (int)Queue1.Peek();
        }

        public int Size()
        {
            return QueueSize;
        }

        public IEnumerator<T> GetEnumerator()
        {
            var list = Queue1.ToArray().Cast<T>().ToList();
            return list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *