offer09 用两个栈实现队列
解答
class CQueue {
public:
CQueue() {
real = 0;
}
void appendTail(int value) {
// 1 2 3 4
// 4 3 2 1
// 入队 加在head上 同步到尾
head.push(value);
++real;
}
int deleteHead() {
if(real <= 0)
{
return -1;
}
else
{
if(tail.empty())
{
// 为空则更新
int len = real;
stack tmp(head);
while(len--)
{
tail.push(tmp.top());
tmp.pop();
}
}
--real;
int result = tail.top();
tail.pop();
return result;
}
}
private:
stack<int> head;
stack<int> tail;
int real;
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
offer30 包含min函数的栈
解答
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
data.push(x);
if(minData.empty())
{
minData.push(x);
}
else
{
if(minData.top() >= x)
{
minData.push(x);
}
}
}
void pop() {
if(data.top() == minData.top())
{
data.pop();
minData.pop();
}
else
{
data.pop();
}
}
int top() {
return data.top();
}
int min() {
return minData.top();
}
private:
stack<int> data;
stack<int> minData;
};
/**
* 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();
*/