一、題目
??實(shí)現(xiàn)一個MyQueue類,該類用兩個棧來實(shí)現(xiàn)一個隊列。
??點(diǎn)擊此處跳轉(zhuǎn)題目。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
說明:文章來源:http://www.zghlxwxcb.cn/news/detail-704655.html
- 你只能使用標(biāo)準(zhǔn)的棧操作 – 也就是只有
push to top
,peek/pop from top
,size
和is empty
操作是合法的。 - 你所使用的語言也許不支持棧。你可以使用
list
或者deque
(雙端隊列)來模擬一個棧,只要是標(biāo)準(zhǔn)的棧操作即可。 - 假設(shè)所有操作都是有效的 (例如,一個空的隊列不會調(diào)用
pop
或者peek
操作)。
二、C# 題解
??很簡單的題目,進(jìn)隊列時將元素壓入 inStack
中,出隊列時將 inStack
元素順序壓入 outStack
后彈出頂端元素即可。文章來源地址http://www.zghlxwxcb.cn/news/detail-704655.html
public class MyQueue {
private Stack<int> inStack, outStack;
/** Initialize your data structure here. */
public MyQueue() {
inStack = new Stack<int>();
outStack = new Stack<int>();
}
/** Push element x to the back of queue. */
public void Push(int x) {
Reverse(outStack, inStack);
inStack.Push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int Pop() {
Reverse(inStack, outStack);
return outStack.Pop();
}
/** Get the front element. */
public int Peek() {
Reverse(inStack, outStack);
return outStack.Peek();
}
/** Returns whether the queue is empty. */
public bool Empty() {
return (inStack.Count | outStack.Count) == 0;
}
// 將 st1 中的元素壓入 st2 中
private void Reverse(Stack<int> st1, Stack<int> st2) {
while (st1.Count != 0) st2.Push(st1.Pop());
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.Push(x);
* int param_2 = obj.Pop();
* int param_3 = obj.Peek();
* bool param_4 = obj.Empty();
*/
- 時間復(fù)雜度:無。
- 空間復(fù)雜度:無。
到了這里,關(guān)于LeetCode 面試題 03.04. 化棧為隊的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!