@kakadee
2016-06-04T07:06:28.000000Z
字数 1152
阅读 1286
编程
算法
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int tmp = 0;
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
if(stack2.empty()){
cout<<"empty!"<<endl;
return 0;
}
else {
tmp = stack2.top();
stack2.pop();
}
while(!stack2.empty()){
stack1.push(stack2.top());
stack2.pop();
}
return tmp;
}
private:
stack<int> stack1;
stack<int> stack2;
};
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
if(pushV.size() == 0)
return false;
int index1 = 0,index2 = 0;
// 模拟栈的操作
stack<int> s;
while(index1 < pushV.size()) {
s.push(pushV[index1++]);
while (index2 < popV.size() && popV[index2] == s.top()){
s.pop();
index2++;
}
}
return s.empty();
}
};
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
class Solution {
public:
void push(int value) {
s.push(value);
if(value <= minNum.top() || minNum.empty())
minNum.push(value);
}
void pop() {
if(s.top() == minNum.top()){
minNum.pop();
}
s.pop();
}
int top() {
return s.top();
}
int min() {
return minNum.top();
}
private:
stack<int> minNum;
stack<int> s;
};