using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyQueue
{
public class MyQueue<T>
{
private bool _isStoredInLeft = true;
private Stack<T> _left = new Stack<T>();
private Stack<T> _right = new Stack<T>();
public bool IsEmpty
{
get
{
if (_isStoredInLeft)
{
return this._left.Count == 0;
}
else
{
return this._right.Count == 0;
}
}
}
public MyQueue() { }
public void Enqueue(T item)
{
Console.WriteLine("##Enqueue start!");
if (this.IsEmpty || this._isStoredInLeft)
{
Console.WriteLine(" **Enqueue - left stack push:" + item.ToString());
this._left.Push(item);
}
else
{
while (this._right.Count != 0)
{
Console.WriteLine(" Enqueue - left stack push:" + this._right.Peek().ToString());
this._left.Push(this._right.Pop());
}
Console.WriteLine(" **Enqueue - left stack push:" + item.ToString());
this._left.Push(item);
this._isStoredInLeft = true;
}
}
public T Dequeue()
{
Console.WriteLine("##Dequeue start!");
if (this.IsEmpty)
{
throw new System.InvalidOperationException("Queue empty");
}
if (this._isStoredInLeft)
{
while (this._left.Count != 0)
{
Console.WriteLine(" Dequeue - right stack push:" + this._left.Peek().ToString());
this._right.Push(this._left.Pop());
}
this._isStoredInLeft = false;
}
Console.WriteLine(" **Dequeue - right stack pop:" + this._right.Peek().ToString());
return this._right.Pop();
}
}
class Test
{
static void Main(string[] args)
{
MyQueue<int> q = new MyQueue<int>();
for (int i = 0; i < 5; i++)
{
q.Enqueue(i);
}
for (int i = 0; i < 3; i++)
{
q.Dequeue();
}
for (int i = 5; i < 10; i++)
{
q.Enqueue(i);
}
while (!q.IsEmpty)
{
q.Dequeue();
}
q.Dequeue();
}
}
}