forked from 5zhu/algorithm-learning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyStack.java
More file actions
56 lines (50 loc) · 1.19 KB
/
Copy pathMyStack.java
File metadata and controls
56 lines (50 loc) · 1.19 KB
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
52
53
54
55
56
package com.algorithdemo.stack;
import java.util.Stack;
/**
* 一个有getMin功能的栈
* 题目描述:实现一个特殊的栈,在栈的基本功能上,再实现返回栈中最小元素的操作
*/
public class MyStack {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack(){
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
/**
* 入栈
* @param num
*/
public void push(int num) {
if(stackMin.isEmpty()){
this.stackData.push(num);
}else if(num <= this.getMin()){
this.stackMin.push(num);
}
this.stackData.push(num);
}
/**
* 出栈
* @return
*/
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;
}
/**
* 返回栈的最小元素
* @return
*/
public int getMin(){
if(this.stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty.");
}
return this.stackMin.peek();
}
}