Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 55b8a0f

Browse files
nextcommit
1 parent 25183f4 commit 55b8a0f

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

‎src/revision/FindMaxinStack.java

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package revision;
2+
3+
import java.util.Stack;
4+
5+
public class FindMaxinStack {
6+
7+
Stack<Integer> stk = new Stack<>();
8+
int max;
9+
10+
public void getMax() {
11+
12+
if (stk.empty()) {
13+
System.out.println("no element");
14+
} else {
15+
System.out.println(max);
16+
}
17+
}
18+
19+
public void peek() {
20+
21+
if (stk.empty()) {
22+
System.out.println("stack is empty");
23+
}
24+
25+
int top = stk.peek();
26+
27+
if (top > max) { // here it means max contains the top element.
28+
System.out.println(max);
29+
} else {
30+
System.out.println(top);
31+
}
32+
33+
}
34+
35+
36+
public void pop() {
37+
38+
if (stk.isEmpty()) {
39+
System.out.println("empty");
40+
return;
41+
}
42+
43+
int top = stk.peek();
44+
stk.pop();
45+
if (top > max) {
46+
System.out.println(max);
47+
max = 2 * max - top;
48+
} else {
49+
System.out.println(top);
50+
}
51+
52+
}
53+
54+
55+
public void push(int elem) {
56+
57+
if (stk.isEmpty()) {
58+
59+
max = elem;
60+
stk.push(elem);
61+
return;
62+
}
63+
64+
if (elem > max) {
65+
stk.push(2 * elem - max);
66+
max = elem;
67+
} else {
68+
stk.push(elem);
69+
}
70+
71+
72+
}
73+
74+
75+
public static void main(String[] args) {
76+
77+
FindMaxinStack obj = new FindMaxinStack();
78+
obj.push(3);
79+
obj.pop();
80+
obj.getMax();
81+
}
82+
83+
84+
85+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /