题目
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
题意
用栈模拟队列的操作。
解法一:入栈时进行处理
需要两个栈,两次倒换即达到队列的效果
例如
q栈中元素为2 1
要push(3)
现将q栈中的元素push()到t栈为: 1 2
push(3)
t栈为:1 2 3
t栈元素依次push()到q栈中为3 2 1。
解法二:只在出栈或者获取栈顶元素时进行处理
处理:栈中倒置一次,栈中元素相反顺序
相比来说,当进行少量pop()和peek()时方法二效率比较高
题解
用两个栈模拟队列的操作
C++代码
方法一
class MyQueue {
public:
stack<int>q;
stack<int>t;
MyQueue() { }
void push(int x) {
while(!q.empty())
{
t.push(q.top());
q.pop();
}
q.push(x);
while(!t.empty())
{
q.push(t.top());
t.pop();
}
}
int pop() {
int res = q.top();
q.pop();
return res;
}
int peek() {
return q.top();
}
bool empty() {
return q.empty();
}
};
方法二:
class MyQueue {
public:
stack<int>q;
stack<int>t;
MyQueue() { }
void push(int x)
{
q.push(x);
}
int pop()
{
if(t.empty())
{
while(!q.empty())
{
t.push(q.top());
q.pop();
}
}
int m = t.top();
t.pop();
return m;
}
int peek() {
if(t.empty())
{
while(!q.empty())
{
t.push(q.top());
q.pop();
}
}
return t.top();
}
bool empty() {
return q.empty()&&t.empty();
}
};
python代码
class MyQueue(object):
def __init__(self):
self.q = []
self.t = []
def push(self, x):
self.q.append(x)
def pop(self):
if len(self.t)==0:
while len(self.q)!=0:
self.t.append(self.q[-1])
self.q.pop()
m = self.t[-1]
self.t.pop()
return m
def peek(self):
if len(self.t)==0:
while len(self.q)!=0:
self.t.append(self.q[-1])
self.q.pop()
return self.t[-1]
def empty(self):
return len(self.q)==0 and len(self.t)==0