题解 | #包含min函数的栈#
包含min函数的栈
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
class Solution { public: void push(int value) { stack1.push(value); } void pop() { stack1.pop(); } int top() { return stack1.top(); } int min() { // 记录当前栈的长度 int len = stack1.size(); int res = stack1.top(); // 记录逆序栈 int arr[len]; for(int i = 0; i < len; i++) { int element = stack1.top(); if(res > element) { res = element; } arr[i] = element; stack1.pop(); } // 数组逆序还原栈 for(int i = (sizeof(arr)/sizeof(arr[0]) - 1) ; i >= 0; i--) { push(arr[i]); } return res; } private: stack<int> stack1; };