这个题脑子里想想就明白了。
class SortedStack {
public:
stack<int>s1, s2;//s1是辅助栈
SortedStack() {
}
void push(int val) {
if (s2.empty())
{
s2.push(val);
return;
}
while (!s2.empty())
{
if (val <= s2.top())
{
break;
}
s1.push(s2.top());
s2.pop();
}
s2.push(val);
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
void pop() {
if (!s2.empty())
s2.pop();
}
int peek() {
if (!s2.empty())
return s2.top();
return -1;
}
bool isEmpty() {
return s2.empty();
}
};
其实,代码还可以更简洁一些:
void push(int val) {
while (!s2.empty() && val > s2.top())
{
s1.push(s2.top());
s2.pop();
}
s2.push(val);
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
class CQueue {
public:
stack<int>s1,s2;
CQueue() {
}
void appendTail(int value) {//入队
s1.push(value);
}
int deleteHead() {//出队列
if(s2.empty()&&s1.empty())
{
return -1;
}
if(!s2.empty())
{
int temp=s2.top();
s2.pop();
return temp;
}
//当s2为空时
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
int temp=s2.top();
s2.pop();
return temp;
}
};
class MinStack {
public:
/** initialize your data structure here. */
//辅助栈
stack<int> mystack;
stack<int> min_stack;
MinStack() {
min_stack.push(INT_MAX);
}
void push(int x) {
mystack.push(x);
min_stack.push(min(x, min_stack.top()));
}
void pop() {
mystack.pop();
min_stack.pop();
}
int top() {
return mystack.top();
}
int getMin() {
return min_stack.top();
}
};