返回栈中的最小值

用另一个栈存放栈的最小值。

import java.util.Stack;


public class Minstack {

	Stack<Integer> minStack;
	Stack<Integer> dataStack;
	public Minstack() {
		this.minStack=new Stack<>();
		this.dataStack=new Stack<>();
	}
	public void push(int num) {
		dataStack.push(num);
		if(minStack.isEmpty()||minStack.peek()>=num)
			minStack.push(num);
		else
			minStack.push(minStack.peek());
	}
	public Integer pop() {
		if(dataStack.isEmpty())
		{
			throw new RuntimeException("dataStack is Empty!");
		}
		if(dataStack.peek()==minStack.peek())
		{
			dataStack.pop();
			return minStack.pop();
		}
		else
		{
			return dataStack.pop();
		}
		
	}
	public int getMin() {
		if(!minStack.isEmpty())
			return minStack.peek();
		throw new RuntimeException("minStack is Empty!");
	}
	public static void main(String[] args) {
		Minstack mstack=new Minstack();
		mstack.push(3);
		mstack.push(5);
		mstack.push(2);
		mstack.push(1);
		
		System.out.println(mstack.getMin());
		mstack.pop();
		System.out.println(mstack.getMin());
		
	}

}

猜你喜欢

转载自blog.csdn.net/qq_42403295/article/details/88595510
今日推荐