题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数
。在该栈中,调用min,push,pop时间复杂度均为o(1)
代码:
package targetOffer;
import java.util.Iterator;
import java.util.Stack;
public class Stack1_21 {
Stack<Integer> data_stack=null;
Stack<Integer> min_stack=null;
public Stack1_21()
{
data_stack=new Stack<Integer>();
min_stack=new Stack<Integer>();
}
void push( int value)
{
data_stack.push(value);
if(min_stack.size()==0||value<min_stack.peek())
{
min_stack.push(value);
}
else
min_stack.push(min_stack.peek());
}
int pop(){
if(!min_stack.isEmpty()&&!data_stack.isEmpty())
{ min_stack.pop();
return data_stack.pop();
}
return -1;
}
public Stack<Integer> getData_stack() {
return data_stack;
}
public void setData_stack(Stack<Integer> dataStack) {
data_stack = dataStack;
}
public Stack<Integer> getMin_stack() {
return min_stack;
}
public void setMin_stack(Stack<Integer> minStack) {
min_stack = minStack;
}
int min()
{
if(!min_stack.isEmpty())
return min_stack.peek();
System.out.print("空\t");
return -1;
}
public static void main(String args[])
{
Stack1_21 test=new Stack1_21();
test.push(3);
test.push(5);
test.push(1);
Stack<Integer> min=test.getMin_stack();
for(Iterator<Integer> it=min.iterator();it.hasNext();)
{
int temp=it.next();
System.out.println(temp+"\t");
}
System.out.println("最小值依次是:");
int temp=test.min();
System.out.println(temp);
test.pop();
temp=test.min();
System.out.println(temp);
test.pop();
temp=test.min();
System.out.println(temp);
}
}
3
3
1
最小值依次是:
1
3
3