思路:題目要求寫一個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