用栈实现队列
leetcode :
Implement the following operations of a queue using stacks.
push
to top, peek/pop from top, size,
and is empty operations are valid.思路:用两个栈,s1,s2,s2只是为了移动数据用的。
class Queue {
public:
stack<int> s1,s2;
// Push element x to the back of queue.
void push(int x) {
s1.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
//将s1内元素除了最后一个全部移动到s2
while(s1.size()>1)
{
s2.push(s1.top());
s1.pop();
}
//最后一个元素删除
s1.pop();
//将s2内元素全部移动到s1
while(s2.size()>0)
{
s1.push(s2.top());
s2.pop();
}
}
// Get the front element.
int peek(void) {
//将s1内元素除了最后一个全部移动到s2
while(s1.size()>1)
{
s2.push(s1.top());
s1.pop();
}
//保存最后一个元素,然后再移动到s2
int res=s1.top();
s2.push(res);
s1.pop();
//将s2内元素全部移动到s1
while(s2.size()>0)
{
s1.push(s2.top());
s2.pop();
}
return res;
}
// Return whether the queue is empty.
bool empty(void) {
return s1.empty();
}
};leetcode:
Implement the following operations of a stack using queues.
push
to back, peek/pop from front, size,
and is empty operations are valid.class Stack {
public:
deque<int> q1,q2;
// Push element x onto stack.
void push(int x) {
q1.push_back(x);
}
// Removes the element on top of the stack.
void pop() {
while(q1.size()>1)//将q1数据除了最后一个外,全部移动到q2
{
q2.push_back(q1.front());
q1.pop_front();
}
q1.pop_front();//删除栈顶元素
while(q2.size()>0)//将q2元素全部移动回到q1
{
q1.push_back(q2.front());
q2.pop_front();
}
}
// Get the top element.
int top() {
while(q1.size()>1)//将q1数据除了最后一个外,全部移动到q2
{
q2.push_back(q1.front());
q1.pop_front();
}
//获取栈顶元素,将其移动到q2
int res=q1.front();
q2.push_back(q1.front());
q1.pop_front();
while(q2.size()>0)//将q2元素全部移动回到q1
{
q1.push_back(q2.front());
q2.pop_front();
}
return res;
}
// Return whether the stack is empty.
bool empty() {
return q1.empty();
}
};版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u013861066/article/details/47207823