栈和队列的常见面试题-返回栈最小元素


)

题目:

实现一个特殊的栈,在基本功能的基础上,再实现返回栈中最小元素的功能**

1 ) 设计的栈类型可以使用现成的栈结构
2 ) pop、push、getMin操作的时间复杂度都是O(1)**

解析:
用两个栈:数据栈,最小元素栈
数据栈:存储栈数据,实现栈的基本功能
最小元素栈:存储栈最小元素,每一次进出栈都会相应操作最小元素

1. java代码写法一:

最小元素栈,在什么情况下都会压入数值最小或栈顶,在什么情况下都会弹出


	public static class MyStack2 {
    
    
		private Stack<Integer> stackData;
		private Stack<Integer> stackMin;

		public MyStack2() {
    
    
			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();//return the top of this stack
				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();
		}
	}

2. java代码写法二:

数值<=最小元素栈顶情况下,最小元素栈才会压入。数值=min栈顶,min栈才会弹出


	public static class MyStack1 {
    
    
		private Stack<Integer> stackData;
		private Stack<Integer> stackMin;

		public MyStack1() {
    
    
			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);
			}
			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();
		}
	}

猜你喜欢

转载自blog.csdn.net/ws13575291650/article/details/113696402
今日推荐