两个栈实现队列

 /// <summary>
    /// 两个栈实现一个队列,利用栈先进后出的原理,栈1 进入栈2的数据顺序就会倒过来,实现,先进先出(队列)
    /// </summary>
    class StackToQueue
    {
        public Stack<int> stack1 = new Stack<int>();
        public Stack<int> stack2 = new Stack<int>();

        /// <summary>
        /// 加入一个值
        /// </summary>
        /// <param name="val"></param>
        public void Put(int val)
        {
            stack1.Push(val);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public int Pop()
        {
            if (stack2.Count > 0)
            {
                return stack2.Pop();
            }
            if (stack1.Count == 0)
            {
                return -1;
            }
            while (stack1.Count > 0)
            {
                stack2.Push(stack1.Pop());
            }
            return stack2.Pop();
        }
    }

 

posted @ 2018-03-28 09:36  丶Pz  阅读(173)  评论(1编辑  收藏  举报