Coding Interviews 20 包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

思路

We need another data structure to sotre the min list.(Use stack may be the best way)

代码

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
public class MinStack {

//方法二:建立辅助栈

Stack<Integer> stack = new Stack<>();
ArrayList<Integer> list = new ArrayList<>();
大专栏  Coding Interviews 20 包含min函数的栈>
/**
* 定义栈的数据结构
* 请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
* @param args
*/
public static void main(String[] args) {

}

public void push(int node) {
stack.push(node);


if(!list.isEmpty()){
int index = 0;
while(index<list.size()){
if(node > list.get(index)){
list.add(index, node);
break;
}
index++;
}

if(index == list.size()){
list.add(node);
}
}else{
list.add(node);
}
}

public void () {
Integer a = stack.pop();
list.remove(a);
}

public int top() {
return stack.peek();
}

public int min() {
return list.get(list.size()-1);
}
}
原文地址:https://www.cnblogs.com/lijianming180/p/12258872.html