Over a million developers have joined DZone.

Queue using 2 Stacks - C#

Queue using 2 Stacks - C#
public class QueueUsing2Stacks
            private Stack _stack1 = new Stack();
            private Stack _stack2 = new Stack();

            public QueueUsing2Stacks() { }

            public void Enqueue(int data)
               //Pop ALL existing elements from stack1, push them onto stack2
                int _stack1Count = _stack1.Count;
                for (int i = 0; i < _stack1Count; i++)
                //Push new data onto stack1

                int _stack2Count = _stack2.Count;
                //Pop ALL elements from stack2 and Push them back onto stack1
                for (int i = 0; i < _stack2Count; i++)

            public int Dequeue()
                if (_stack1.Count == 0)
                    throw new Exception("Queue is Empty");

                return _stack1.Pop();

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}