我是靠谱客的博主 精明墨镜,这篇文章主要介绍实现getMin功能的栈,现在分享给大家,希望可以做个参考。

第一种方式:


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Stack; public class MyStack1 { public static void main(String[] args) { MyStack1Real myStack1Real = new MyStack1Real(); for (int i = 0; i < 10; i++) { myStack1Real.push(i); } myStack1Real.push(-1); System.out.println(myStack1Real.getMin()); } } class MyStack1Real { private Stack<Integer> stackData; private Stack<Integer> stackMin; public MyStack1Real() { this.stackData = new Stack<Integer>(); this.stackMin = new Stack<Integer>(); } public void push(int newNum) { if (stackMin.isEmpty()) { stackMin.push(newNum); } else if (newNum <= this.getMin()) { stackMin.push(newNum); } stackData.push(newNum); } public int pop() { if (this.stackData.peek() == this.stackMin.peek()) { this.stackData.pop(); return this.stackMin.pop(); } else { return this.stackMin.pop(); } } public int getMin() { if (this.stackMin.isEmpty()) { throw new RuntimeException("your stack is empty!"); } else { return this.stackMin.peek(); } } }

第二种方式:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package stackAndQueue; import java.util.Stack; public class MyStack2 { public static void main(String[] args) { MyStack1Real myStack1Real = new MyStack1Real(); for (int i = 0; i < 10; i++) { myStack1Real.push(i); } myStack1Real.push(-8); System.out.println(myStack1Real.getMin()); } } class MyStack2Real { private Stack<Integer> stackData; private Stack<Integer> stackMin; public MyStack2Real() { this.stackData = new Stack<Integer>(); this.stackMin = new Stack<Integer>(); } public void push(int newNum) { if (this.stackMin.isEmpty()) { this.stackData.push(newNum); this.stackMin.push(newNum); } else if (newNum <= this.getMin()) { this.stackData.push(newNum); this.stackMin.push(newNum); } else { this.stackData.push(newNum); this.stackMin.push(this.stackMin.peek()); } } public int pop(int newNum) { this.stackMin.pop(); return this.stackData.pop(); } public int getMin() { if (this.stackMin.isEmpty()) { throw new RuntimeException("your stack is empty"); } else { return stackMin.peek(); } } }


最后

以上就是精明墨镜最近收集整理的关于实现getMin功能的栈的全部内容,更多相关实现getMin功能内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(82)

评论列表共有 0 条评论

立即
投稿
返回
顶部