队列的应用实例
用队列实现栈
题目描述:
- 要用队列去模拟实现栈的话,至少需要两个队列
- 入栈的话,就是哪个队列里面是有元素的,就把元素入到哪个队列中
- 出栈的话, 把有元素的哪个栈的前n-1个元素挪到空的那个栈里面,然后把剩下的那一个元素出栈就可以了
代码如下所示:
class MyStack {
public:
queue<int> q1, q2;
MyStack() {
}
void push(int x) {
if(q1.empty()){
q2.push(x);
return;
}
if(q2.empty()){
q1.push(x);
return;
}
}
int pop() {
int t;
if(q1.empty()){
if(q2.size() == 1){
t = q2.front();
q2.pop();
return t;
}
else{
while(q2.size() > 1){
q1.push(q2.front());
q2.pop();
}
t = q2.front();
q2.pop();
return t;
}
}
if(q2.empty()){
if(q1.size() == 1){
t = q1.front();
q1.pop();
return t;
}
else{
while(q1.size() > 1){
q2.push(q1.front());
q1.pop();
}
t = q1.front();
q1.pop();
return t;
}
}
return 0;
}
int top() {
if(q1.empty())
return q2.back();
else
return q1.back();
}
bool empty() {
return q1.empty() && q2.empty();
}
};
用栈实现队列
题目描述
- 同样的,用一个栈来实现队列是不可以的,所以如果要用栈来模拟实现队列的话,也是需要用到两个栈来实现队列的
代码如下所示:
class MyQueue {
private:
stack<int> st1; //主
stack<int> st2; //辅
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(!st2.empty()){
st1.push(st2.top());
st2.pop();
}
st1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
int ans = st2.top();
st2.pop();
return ans;
}
/** Get the front element. */
int peek() {
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
return st2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
if(st1.empty() && st2.empty()) return true;
else return false;
}
};
/**
* 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();
*/