[力扣] 算法 232 (C#)

232. 用栈实现队列

public class MyQueue
{
    Stack<int> front = new Stack<int>();
    Stack<int> back = new Stack<int>();
    public MyQueue() { }
    public void Push(int x) => front.Push(x);
    public int Pop()
    {
        TryFront2Back();
        return back.Pop();
    }
    public int Peek()
    {
        TryFront2Back();
        return back.Peek();
    }
    void TryFront2Back()
    {
        if (back.Count == 0)
            while (front.Count > 0)
                back.Push(front.Pop());
    }
    public bool Empty() => front.Count + back.Count == 0;
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注