棧——設計一個有getmin功能的棧

題目:實現一個特殊的棧,在實現棧的基本功能的基礎上,再實現返回棧中最小元素的操作。

要求:
1、pop、push、getMin操作的時間複雜度都是O(1)。
2、設計的棧類型可以輸用現成的棧結構。


思路:使用兩個棧,一個用來保存棧中的元素,另一個用於保存每步的最小值
 其實就是左神的思路啦~
代碼:
package getmin;

import java.util.Stack;

import javax.management.RuntimeErrorException;

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{
			this.stackData.push(newNum);
		}
	}
	
	public int pop(){
		if(this.stackData.isEmpty()){
			throw new RuntimeException("your stack is empty");
		}
		int value = this.stackData.pop();
		if(value == this.getmin()){
			this.stackMin.pop();
		}
		return value;
	}
	
	public int getmin(){
		if(this.stackMin.isEmpty()){
			throw new RuntimeException("your stack is empty");
		}
		return this.stackMin.peek();
	}

public static void main(String args[])
{
	MyStack sta = new MyStack();
	sta.push(3);
	sta.push(4);
	sta.push(2);
	sta.push(1);
	sta.pop();
	int min = sta.getmin();
	System.out.println(min);
}

}









發佈了38 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章