使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
前先翻阅 LeetCode 用队列实现栈
队列:先进先出特性,只能在队头出队,队尾入队操作。
栈:先进后出特性,只能在栈顶出栈、入栈操作。
双端队列:队头、队尾都可进行入队、出队操作。
方法一:使用双端队列实现。
class MyQueue {
private:
deque<int> myDeque;//双端队列
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {//队尾入队
myDeque.push_back(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {//队头出队
int top = myDeque.front();
myDeque.pop_front();//队头出队
return top;
}
/** Get the front element. */
int peek() {//返回队头
return myDeque.front();
}
/** Returns whether the queue is empty. */
bool empty() {
return myDeque.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();
*/
但是感觉使用这种方法有点不厚道,斜眼/斜眼
方法二:使用栈实现。
class MyQueue {
private:
stack<int> firstStack;//主栈
stack<int> secondStack;//辅栈
//将stackOne中的所有元素放置到stackTwo中
void turnStack(stack<int> &stackOne, stack<int> &stackTwo) {
while (!stackOne.empty()) {
stackTwo.push(stackOne.top());
stackOne.pop();
}
}
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {//队尾入队(主栈进行栈
firstStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {//队头出队,主栈出栈底
turnStack(firstStack, secondStack);//将主栈中元素全部放入辅栈
int top = secondStack.top();//辅栈现在的顶部就是队列的头部
secondStack.pop();//辅栈出栈
turnStack(secondStack, firstStack);//现在将辅栈的所有元素放回主栈
return top;
}
/** Get the front element. */
int peek() {//返回队头(主栈栈底)
turnStack(firstStack, secondStack);//将主栈中元素全部放入辅栈
int top = secondStack.top();//辅栈现在的顶部就是队列的头部
turnStack(secondStack, firstStack);//现在将辅栈的所有元素放回主栈
return top;
}
/** Returns whether the queue is empty. */
bool empty() {
return firstStack.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();
*/