思路:题目要求写一个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
本文介绍了一种使用辅助栈来实现对一个栈内元素最小值的查询算法,该算法能够在不改变原栈结构的前提下找到栈中当前的最小元素。

被折叠的 条评论
为什么被折叠?



