您的位置:首页 > 其它

《Cracking the Coding Interview》——第3章:栈和队列——题目2

2014-03-18 05:16 579 查看
2014-03-18 05:08

题目:实现一个栈,除了能进行push和pop之外,还能在O(1)时间内返回栈中最小的元素。

解法:用另一个“最小栈”存放最小的元素,每当有不小于当前最小值的元素进栈时,就代表最小值更新了(就算与当前最小值相等,也代表个数变了)。这时,同时要将最小值进栈。这个最小栈的栈顶就是最小的元素。出栈时,遇到数据栈的栈顶元素与最小栈相等时,要同时将最小栈出栈;否则只弹出数据栈即可。

代码:

// 3.2 Design a modified stack that in addition to Push and Pop can also provide minimum element present in the stack via Min function.
#include <climits>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;

class MinStack {
public:
bool empty() {
return st.empty();
}

void push(int val) {
st.push(val);
if (min_st.empty() || val <= min_st.top()) {
min_st.push(val);
}
}

void pop() {
if (st.empty()) {
return;
}
if (st.top() == min_st.top()) {
min_st.pop();
}
st.pop();
}

int top() {
if (st.empty()) {
return INT_MIN;
}
return st.top();
}

int min() {
if (st.empty()) {
return INT_MIN;
}
return min_st.top();
}
private:
stack<int> st;
stack<int> min_st;
};

int main()
{
char s[100];
int op;
MinStack st;

while (scanf("%s", s) == 1 && strcmp(s, "END") != 0) {
if (strcmp(s, "PUSH") == 0) {
scanf("%d", &op);
st.push(op);
printf("push=%d\n", op);
} else if (strcmp(s, "POP") == 0) {
op = st.top();
st.pop();
printf("pop=%d\n", op);
} else if (strcmp(s, "TOP") == 0) {
printf("top=%d\n", st.top());
} else if (strcmp(s, "MIN") == 0) {
printf("min=%d\n", st.min());
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: