码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode225

时间:2017-04-25 00:49:02      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:anti   call   http   object   ack   targe   tco   script   empty   

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

标签:anti   call   http   object   ack   targe   tco   script   empty   

原文地址:http://www.cnblogs.com/asenyang/p/6759573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!