思路:题目要求写一个min函数,求栈中的最小值,栈要比较大小,必须pop出来,题目只需要求最小值,所以栈的结构不能变,因此需要额外的辅助栈保存数据,最后导回来
代码:
import java.util.Stack;
public class Solution {
Stack stack = new Stack();
public void push(int node) {
stack.push(node);
}
public void pop() {
stack.pop();
}
public int top() {
return (int)stack.pop();
}
public int min() {
Stack stack1 = new Stack();
int min=(int)stack.pop();
stack1.push(min);
int temp = 0;
while(!stack.isEmpty()){
temp = (int)stack.pop();
stack1.push(temp);
if(temp < min){
min = temp;
}
}
while(!stack1.isEmpty()){
stack.push(stack1.pop());
}
return min;
}
}
end