题目01:
class MinStack {
public:
/** initialize your data structure here. */
stack<int>stack1;
stack<int>stack2;
MinStack() {
}
void push(int x) {
stack1.push(x);
if(stack2.empty() || stack2.top()>=x)
stack2.push(x);
}
void pop() {
//保持 stack1 和stack2的一致性
// 这里就不用重复压入stack2的顶部数据!
int tmp1 = stack1.top();
int tmp2 = stack2.top();
stack1.pop();
if(tmp1==tmp2){
//stack1.pop();
stack2.pop();
}
// return tmp2;
}
int top() {
return stack1.top();
}
int min() {
int temp = stack2.top();
//stack2.pop();
return temp;
}
};
题目2:
class CQueue {
public:
CQueue() {
}
stack<int>stack1;
stack<int>stack2;
void appendTail(int value) {
// 队尾插入 直接插入stack1
stack1.push(value);
}
int deleteHead() {
//如果stack2 就出栈
//如果stack1不为空,就插入stack2
if(!stack2.empty()){
int temp = stack2.top();
stack2.pop();
return temp;
}
if(stack1.empty())
return -1;
while(!stack1.empty()){
int tmp = stack1.top();
stack2.push(tmp);
stack1.pop();
}
int tm = stack2.top();
stack2.pop();
return tm;
}
};