目錄
- 題目描述:
- 示例:
- 說明:
- 解法:
題目描述:
使用棧實現隊列的下列操作:
- push(x) -- 將一個元素放入隊列的尾部。
- pop() -- 從隊列首部移除元素。
- peek() -- 返回隊列首部的元素。
- empty() -- 返回隊列是否為空。
示例:
MyQueue queue = new MyQueue();queue.push(1);queue.push(2); queue.peek(); // 返回 1queue.pop(); // 返回 1queue.empty(); // 返回 false
說明:
- 你只能使用標準的棧操作 -- 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標準的棧操作即可。
- 假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)。
解法:
class MyQueue {
public:/** Initialize your data structure here. */stack<int> stk;MyQueue() {}/** Push element x to the back of queue. */void push(int x) {stk.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {stack<int> tmp;while(!stk.empty()){tmp.push(stk.top());stk.pop();}int res = tmp.top();tmp.pop();while(!tmp.empty()){stk.push(tmp.top());tmp.pop();}return res;}/** Get the front element. */int peek() {stack<int> tmp;while(!stk.empty()){tmp.push(stk.top());stk.pop();}int res = tmp.top();while(!tmp.empty()){stk.push(tmp.top());tmp.pop();}return res;}/** Returns whether the queue is empty. */bool empty() {return stk.empty();}
};/*** 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();*/