09.用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
思路:
当删除元素时,先判断输出栈是否有元素:
- 如果没有元素,判断输入栈是否为空:
- 如果输入栈也为空,返回-1,表示全都为空;
- 如果输入栈不为空,将输入栈的元素依次弹出压入输出栈中,随后弹出输出栈栈首元素
- 如果有元素,直接弹出栈首元素
class CQueue {
public:
stack<int> st_in;
stack<int> st_out;
CQueue() {}
void appendTail(int value) { st_in.push(value); }
int deleteHead() {
if (st_out.empty()) {
if (st_in.empty()) {
return -1;
}
while (!st_in.empty()) {
st_out.push(st_in.top());
st_in.pop();
}
}
int value = st_out.top();
st_out.pop();
return value;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
30.包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
class MinStack {
public:
/** initialize your data structure here. */
stack<int> st, min_st;
MinStack() { min_st.push(INT_MAX); }
void push(int x) {
st.push(x);
//最小值时刻都在改变,需要使用min_st栈顶元素
min_st.push(std::min(min_st.top(), x));
}
void pop() {
min_st.pop();
st.pop();
}
int top() { return st.top(); }
int min() { return min_st.top(); }
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->min();
*/