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

2014-03-18 05:08

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

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

代码:

 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.

 2 #include <climits>

 3 #include <cstdio>

 4 #include <cstring>

 5 #include <stack>

 6 using namespace std;

 7 

 8 class MinStack {

 9 public:

10     bool empty() {

11         return st.empty();

12     }

13     

14     void push(int val) {

15         st.push(val);

16         if (min_st.empty() || val <= min_st.top()) {

17             min_st.push(val);

18         }

19     }

20     

21     void pop() {

22         if (st.empty()) {

23             return;

24         }

25         if (st.top() == min_st.top()) {

26             min_st.pop();

27         }

28         st.pop();

29     }

30     

31     int top() {

32         if (st.empty()) {

33             return INT_MIN;

34         }

35         return st.top();

36     }

37     

38     int min() {

39         if (st.empty()) {

40             return INT_MIN;

41         }

42         return min_st.top();

43     }

44 private:

45     stack<int> st;

46     stack<int> min_st;

47 };

48 

49 int main()

50 {

51     char s[100];

52     int op;

53     MinStack st;

54     

55     while (scanf("%s", s) == 1 && strcmp(s, "END") != 0) {

56         if (strcmp(s, "PUSH") == 0) {

57             scanf("%d", &op);

58             st.push(op);

59             printf("push=%d\n", op);

60         } else if (strcmp(s, "POP") == 0) {

61             op = st.top();

62             st.pop();

63             printf("pop=%d\n", op);

64         } else if (strcmp(s, "TOP") == 0) {

65             printf("top=%d\n", st.top());

66         } else if (strcmp(s, "MIN") == 0) {

67             printf("min=%d\n", st.min());

68         }

69     }

70     

71     return 0;

72 }

 

你可能感兴趣的:(interview)