本文包含的Leetcode题目
- 用队列实现栈(Leetcode 225)
- 用栈实现队列(Leetcode 232)
Leetcode 225:用队列实现栈
准备两个queue:q1, q2
每次将元素先放入q2,然后将q1元素全部放入q2,再将q1和q2交换,这样能够保证每次最后进入的元素都在队列q1的最前端,实现栈逻辑。
class MyStack {
public:
queue<int> queue1;
queue<int> queue2;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
queue2.push(x);
while (!queue1.empty()) {
queue2.push(queue1.front());
queue1.pop();
}
swap(queue1, queue2);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int r = queue1.front();
queue1.pop();
return r;
}
/** Get the top element. */
int top() {
int r = queue1.front();
return r;
}
/** Returns whether the stack is empty. */
bool empty() {
return queue1.empty();
}
};
Leetcode 232:用栈实现队列
准备两个栈s1,s2 s1用来存放数据,s2用来颠倒数据并弹出
class MyQueue {
public:
stack<int> s1;
stack<int> s2;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (s2.empty()) {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
int res = s2.top();
s2.pop();
return res;
}
/** Get the front element. */
int peek() {
int res = this->pop(); //peek操作可以直接调用pop()
s2.push(res);
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty() && s2.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();
*/