C#LeetCode刷題之#225-用佇列實現棧(Implement Stack using Queues)
問題
使用佇列實現棧的下列操作:
push(x) -- 元素 x 入棧 pop() -- 移除棧頂元素 top() -- 獲取棧頂元素 empty() -- 返回棧是否為空
注意:
你只能使用佇列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。 你所使用的語言也許不支援佇列。 你可以使用 list 或者 deque(雙端佇列)來模擬一個佇列 , 只要是標準的佇列操作即可。 你可以假設所有操作都是有效的(例如, 對一個空的棧不會呼叫 pop 或者 top 操作)。
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. empty() -- Return whether the stack is empty.
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
示例
public class Program {
public static void Main(string[] args) {
var stack = new MyStack();
stack.Push(1);
stack.Push(2);
stack.Push(3);
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Empty());
Console.ReadKey();
}
public class MyStack {
private Queue<int> _queue = null;
public MyStack() {
_queue = new Queue<int>();
}
public void Push(int x) {
//基本思路是反轉原佇列
var queue = new Queue<int>();
queue.Enqueue(x);
foreach(var elemet in _queue) {
queue.Enqueue(elemet);
}
_queue = queue;
}
public int Pop() {
return _queue.Dequeue();
}
public int Top() {
return _queue.First();
}
public bool Empty() {
return !_queue.Any();
}
}
}
以上給出1種演算法實現,以下是這個案例的輸出結果:
3
2
1
True
分析:
顯而易見,Push 的時間複雜度應當為: ,其它方法的時間複雜度應當為: 。