225. 用队列实现栈
使用队列实现栈的下列操作:
- push(x) -- 元素 x 入栈
- pop() -- 移除栈顶元素
- top() -- 获取栈顶元素
- empty() -- 返回栈是否为空
class MyStack {
public:
/** Initialize your data structure here. */
queue<int> q;
int top_ele = -1;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
top_ele=x;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size=q.size();
while(size>2)
{
int tmp=q.front();
q.pop();
q.push(tmp);
size--;
}
//原队列倒数第二个元素是栈pop后的栈顶元素,更新top_ele
top_ele=q.front();
q.pop();
q.push(top_ele);
//原队列倒数第一个元素是栈pop的元素
int tmp=q.front();
q.pop();
return tmp;
}
/** Get the top element. */
int top() {
return top_ele;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
使用一个变量随时获取队尾元素也就是栈顶元素,只在pop时更新队列。这样比在push时更新队列,pop和top时队列已经是更新过的更好一些。
232. 用栈实现队列
使用栈实现队列的下列操作:
- push(x) -- 将一个元素放入队列的尾部。
- pop() -- 从队列首部移除元素。
- peek() -- 返回队列首部的元素。
- empty() -- 返回队列是否为空。
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> s1;
stack<int> s2;
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())
{
int tmp=s1.top();
s2.push(tmp);
s1.pop();
}
}
int tmp=s2.top();
s2.pop();
return tmp;
}
/** Get the front element. */
int peek() {
if(s2.empty())
{
while(!s1.empty())
{
int tmp=s1.top();
s2.push(tmp);
s1.pop();
}
}
return s2.top();
}
/** 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();
*/
两个栈模拟队列,在pop和peelk时对栈进行翻转,翻转成的栈中元素的顺序为队列中元素的顺序。
网友评论