首页 > 代码库 > leetcode232

leetcode232

public class MyQueue
    {
        Stack<int> S = new Stack<int>();
        /** Initialize your data structure here. */
        public MyQueue()
        {

        }

        /** Push element x to the back of queue. */
        public void Push(int x)
        {
            S.Push(x);
        }

        /** Removes the element from in front of queue and returns that element. */
        public int Pop()
        {
            List<int> list = new List<int>();
            var x = -1;
            while (S.Count > 0)
            {
                x = S.Pop();
                list.Add(x);
            }

            for (int i = list.Count - 2; i >= 0; i--)
            {
                S.Push(list[i]);
            }

            return x;
        }

        /** Get the front element. */
        public int Peek()
        {
            if (S.Count > 0)
            {
                return S.ElementAt(S.Count - 1);
            }
            else
            {
                return -1;
            }
        }

        /** Returns whether the queue is empty. */
        public bool Empty()
        {
            return S.Count == 0;
        }
    }

    /**
     * Your MyQueue object will be instantiated and called as such:
     * MyQueue obj = new MyQueue();
     * obj.Push(x);
     * int param_2 = obj.Pop();
     * int param_3 = obj.Peek();
     * bool param_4 = obj.Empty();
     */

https://leetcode.com/problems/implement-queue-using-stacks/#/description

leetcode232