Reprint please indicate the source http://www.cnblogs.com/haozhengfei/p/68c25fbc949e663f5bb8627a764158f8.html
Can query the most value of the stack exercises
a stack exercise that can query the maximum valueThe 2nd section can query the maximum value of the stack exercises to define the data structure of the stack, in this type to implement a can get the minimum stack element of the Min function.Java (javac 1.7)Code Auto-Complete1
Import Java. util. Stack;
2
3
Public class Solution {
4
Private Stack < Integer > Stackdata = New Stack <> ();
5
Private Stack < Integer > Stackmin = New Stack <> ();
6
7
Public void Push (intnode) {
8
Presses the current element into the stack
9
Stackdata. Push (node);
10
11
/**
12
* If the minimum stack is empty, then press in directly
13
* Otherwise if the current element is less than the top element of the stackmin, press in directly, greater than continue pressing into the top element of the Stackmin
14
*/
15
if (stackmin. IsEmpty ()){
16
stackmin. Push (node);
17
Else {
18
if (node<stackmin. Peek (). Intvalue ()) {
19
stackmin. Push (node);
20
}
21st
Else {
22
stackmin. Push (stackmin. Peek ());
23
}
24
}
25
}
26
27
Public void Pop () {
28
Stackdata. Pop ();
29
stackmin. Pop ();
30
}
31
32
Public int Top () {
33
return Stackdata. Peek ();
34
35
}
36
37
Public int min {
38
return stackmin. Peek ();
39
}
40
}
Your code is saved
The answer is right: Congratulations! The program you submitted passed all of the test casesRun
Algorithm--can query the most value of the stack exercises