标签:
public class Solution{ /** * @param args */ Stack<Integer> stack = new Stack<Integer>(); public void push(int node) { stack.push(node); } public void pop() { stack.pop(); } public int top() { return stack.peek();//这里的top值是用.peek()函数,不要忘记了栈本身的内部函数 } public int min() { int min = stack.peek();//第一个数出栈 int tmp = 0; Iterator<Integer> iterator = stack.iterator();//迭代,以此出栈 while (iterator.hasNext()){ tmp = iterator.next(); if (min>tmp){ min = tmp; } } return min; } public static void main(String[] args)throws Exception { // TODO Auto-generated method stub min_stack ms=new min_stack(); ms.push(3); ms.push(2); ms.push(3); System.out.println(ms.min()); } }
解法二:
思路:用一个栈data保存数据,用另一个栈min保存以此入栈的最小数。如:data中以次入栈:5,4,3,8,9,10,111,12,1
则min中以次入栈:5,4,3,1
每次入栈的时候,如果入栈的元素比min中的栈顶元素小或等于则入栈,否则不如栈。
public class Solution{ Stack<Integer> data = new Stack<Integer>(); Stack<Integer> min = new Stack<Integer>(); Integer temp=null; public void push(int node){ if(temp!=null){ if(node < temp){ min.push(node); temp = node;//temp保存的是最小值 } data.push(node); }else{ temp = node; data.push(node); min.push(node); } } public int pop(){ int num = data.pop(); int num2 = min.pop(); if(num != num2){//判断栈min中是否已经存在了 min.push(num2); } } public int top(){ int num = data.pop(); data.push(num); return num; } public int min(){ int num = min.pop(); min.push(num); return num; } }
解法三:
/*
* 1.dataStack为存储数据的栈,minStack为存储最小值的栈;
* 2.push的时候将value值与minStack中的top值比较,小则minStack push value,大则push top值
*/
class Solution { public: stack<int> dataStack, minStack; void push(int value) { dataStack.push(value); if (minStack.empty()) { minStack.push(value); } else{ int min = minStack.peek();
if(value<min){
minStack.push(value);
}else{
minStack.push(min);
}
}
} void pop() { dataStack.pop(); minStack.pop(); } int top() { return dataStack.peek(); } int min() { return minStack.peek(); } };
标签:
原文地址:http://www.cnblogs.com/tjuxqcui/p/5537838.html