有苦有乐的算法 --- 自定义一个栈,实现压栈(push)、弹栈(pop)、获取站内最小值(getmin)

题目

自己定义一个栈的class,要求此栈有三个方法push、pop、getmin
push:往栈中压入一个数据
pop:从栈中弹出一个数据
gitmin:过去这个栈中最小的数据单不弹出

解析

准备两个栈stackData、stackMin

压栈时,
stackData压入数据;
stackMin栈顶数据大于需要压入的数据,stackMin也压入这个数据,stackMin栈顶数据小于需要压入的数据,重复压入stackMin栈顶数据。
例如需要压入的数据依次是:[4,7,3,5,1]

弹栈时,stackData与stackMin一起弹出即可

代码

public class MyStack {
	private Stack<Integer> stackData;
	private Stack<Integer> stackMin;
	
	public MyStack() {
		this.stackData = new Stack<Integer>();
		this.stackMin = new Stack<Integer>();
	}
	
	public void push(int newNum) {
		if (this.stackMin.isEmpty()) {
			this.stackMin.push(newNum);
		} else if (newNum < this.getmin()) {
			this.stackMin.push(newNum);
		} else {
			int newMin = this.stackMin.peek();
			this.stackMin.push(newMin);
		}
		this.stackData.push(newNum);
	}
	
	public int pop() {
		if (this.stackData.isEmpty()) {
			throw new RuntimeException("Your stack is empty.");
		}
		this.stackMin.pop();
		return this.stackData.pop();
	}
	
	public int getmin() {
		if (this.stackMin.isEmpty()) {
			throw new RuntimeException("Your stack is empty.");
		}
		return this.stackMin.peek();
	}
}
posted @ 2022-03-07 18:03  叕叕666  阅读(76)  评论(0)    收藏  举报