首页 > 代码库 > leetcode225

leetcode225

public class MyStack
    {
        Queue<int> Q = new Queue<int>();

        /** Initialize your data structure here. */
        public MyStack()
        {

        }

        /** Push element x onto stack. */
        public void Push(int x)
        {
            Q.Enqueue(x);
        }

        /** Removes the element on top of the stack and returns that element. */
        public int Pop()
        {
            var tempQ = new Queue<int>();

            var pop = -1;

            while (Q.Count > 0)
            {
                var cur = Q.Dequeue();

                if (Q.Count == 0)
                {
                    pop = cur;
                }
                else
                {
                    tempQ.Enqueue(cur);
                }
            }

            while (tempQ.Count > 0)
            {
                var cur = tempQ.Dequeue();
                Q.Enqueue(cur);
            }

            return pop;
        }

        /** Get the top element. */
        public int Top()
        {
            var tempQ = new Queue<int>();

            var pop = -1;

            while (Q.Count > 0)
            {
                var cur = Q.Dequeue();
                if (Q.Count == 0)
                {
                    pop = cur;
                }

                tempQ.Enqueue(cur);                
            }

            while (tempQ.Count > 0)
            {
                var cur = tempQ.Dequeue();
                Q.Enqueue(cur);
            }

            return pop;
        }

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

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

https://leetcode.com/problems/implement-stack-using-queues/#/description

leetcode225