本题考查栈的使用。

C++版本

#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

// 定义数据栈
stack<int> stack1;
// 定义辅助栈
stack<int> stack2;

void push(int value){
    // 需要遍历辅助栈中最小的值
    if(stack2.size() == 0 || value < stack2.top())
        stack2.push(value);
    else
        stack2.push(stack2.top());
    stack1.push(value);
}

// 弹出栈顶元素
void pop(){
    stack1.pop();
    stack2.pop();
}

int top(){
    return stack1.top();
}

int min(){
    return stack2.top();
}
int main()
{
    push(3);
    cout<<min()<<endl;
    push(4);
    cout<<min()<<endl;
    push(2);
    cout<<min()<<endl;
    push(1);
    cout<<min()<<endl;
    pop();
    cout<<min()<<endl;
    pop();
    cout<<min()<<endl;
    push(0);
    cout<<min()<<endl;
    return 0;
}

相关文章:

  • 2021-11-09
  • 2021-10-03
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-20
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
  • 2022-02-03
  • 2021-11-01
  • 2022-01-10
相关资源
相似解决方案