Implement Stack using Two Queues

后端 未结 23 826
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

23条回答
  •  甜味超标
    2020-11-28 17:44

    Can we just use one queue to implement a stack? I can use two queues, but considering single queue would be more efficient. Here is the code:

        public void Push(T val)
        {
            queLower.Enqueue(val);
        }
    
        public  T Pop()
        {
    
            if (queLower.Count == 0 )
            {
                Console.Write("Stack is empty!");
                return default(T);
    
             }
            if (queLower.Count > 0)
            {
                for (int i = 0; i < queLower.Count - 1;i++ )
                {
                    queLower.Enqueue(queLower.Dequeue ());
               }
                        }
    
            return queLower.Dequeue();
    
        }
    

提交回复
热议问题