# 剑指offer（五）栈和队列

## 面试题7：用两个栈实现队列

class Solution
{
public:
void push(int node) {
stack1.push(node);
}

int pop() {
if(stack2.size()<=0){
while(stack1.size()>0){
int node = stack1.top();
stack1.pop();
stack2.push(node);
}
}
int res = stack2.top();
stack2.pop();
return res;
}

private:
stack<int> stack1;
stack<int> stack2;
};

class Solution
{
public:
void push(int node) {
if(queue2.size()>0)
queue2.push(node);
else
queue1.push(node);
}

int pop() {
int res;
if(queue1.size()>=1){
while(queue1.size()>1){
int node = queue1.top();
queue1.pop();
queue2.push(node);
}
res = queue1.top();
queue1.pop();
return res;
}
if(queue2.size()>=1){
while(queue2.size()>1){
int node = queue2.top();
queue2.pop();
queue1.push(node);
}
res = queue2.top();
queue2.pop();
return res;
}
return -1;
}

private:
stack<int> queue1;
stack<int> queue2;
};

## 面试题21：包含min函数的栈

class Solution {
public:
void push(int value) {
m_data.push(value);
if(m_min.size()==0 || value<m_min.top())
m_min.push(value);
else
m_min.push(m_min.top());
}
void pop() {
m_data.pop();
m_min.pop();
}
int top() {
return m_data.top();
}
int min() {
return m_min.top();
}
private:
stack<int> m_data,m_min;
};

## 面试题22：栈的压入、弹出序列

class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
bool isPossible = false;
int len = pushV.size();
int pushIndex = 0, popIndex = 0;
stack<int> data;
while(popIndex < len){
while(data.empty() || data.top()!=popV[popIndex]){
if(pushIndex >= len)
break;
data.push(pushV[pushIndex++]);
}//此时要么pushV中的数据都已入栈，要么已经找到与popV[popIndex]相同的数
if(data.top()!=popV[popIndex])
break;
data.pop();
popIndex++;
}
if(popIndex == len && data.empty())
isPossible = true;
return isPossible;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120