我是靠谱客的博主 矮小黑米,这篇文章主要介绍GetMin功能的栈,现在分享给大家,希望可以做个参考。


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

学习算法和数据结构中,买了本书,把书上的题目练习一下

本题难度:士

要求pop、push、getMin操作的时间复杂度为O(1)

代码如下

复制代码
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
45
46
47
48
49
50
51
package stackgame; import java.util.Stack; public class Stack1 { private Stack<Integer> stackData; private Stack<Integer> stackMin; public Stack1() { 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 == getMin()) { 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) { Stack1 sc=new Stack1(); sc.push(5); sc.push(3); sc.push(2); sc.push(4); sc.push(8); System.out.println(sc.getMin()); System.out.print(sc.stackMin.pop()+" "); System.out.print(sc.stackMin.pop()+" "); System.out.println(sc.stackMin.pop()+" "); System.out.print(sc.stackData.pop()+" "); System.out.print(sc.stackData.pop()+" "); System.out.print(sc.stackData.pop()+" "); System.out.print(sc.stackData.pop()+" "); System.out.print(sc.stackData.pop()+" "); } }

结果:

复制代码
1
2
3
2 2 3 5 8 4 2 3 5

最后

以上就是矮小黑米最近收集整理的关于GetMin功能的栈的全部内容,更多相关GetMin功能内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部