/// <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(); } }