Skip to content

Commit 68dbd74

Browse files
committed
Stacks and Queues
1 parent e216469 commit 68dbd74

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package chapter03StacksAndQueues;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
*
7+
* @author chengfeili
8+
* Jun 16, 2017 11:49:18 AM
9+
*
10+
* Problem:
11+
*
12+
* Solution:
13+
*
14+
*/
15+
public class ImplementQueueUsingStacks {
16+
Stack<Integer> input = new Stack<>();
17+
Stack<Integer> output = new Stack<>();
18+
19+
public void push(int x) {
20+
input.push(x);
21+
}
22+
23+
public void pop() {
24+
shift();
25+
output.pop();
26+
}
27+
28+
public int peek() {
29+
shift();
30+
return output.peek();
31+
}
32+
33+
public boolean empty() {
34+
return input.isEmpty() && output.isEmpty();
35+
}
36+
37+
public void shift() {
38+
if (output.isEmpty()) {
39+
while (!input.isEmpty())
40+
output.push(input.pop());
41+
}
42+
}
43+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package chapter03StacksAndQueues;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
*
7+
* @author chengfeili
8+
* Jun 16, 2017 11:07:40 AM
9+
*
10+
* Problem: How would you design a stack which, in addition to push and
11+
* pop, has a function min which returns the minimum element? Push, pop
12+
* and min should all operate in 0(1) time.
13+
*
14+
* Solution: Use an additional stack which keeps track of the mins.
15+
*
16+
*/
17+
public class MinStack extends Stack<Integer> {
18+
private Stack<Integer> stack2 = new Stack<>();
19+
20+
public void push(int val) {
21+
// must be <=
22+
if (val <= min()) {
23+
stack2.push(val);
24+
}
25+
super.push(val);
26+
}
27+
28+
public Integer pop() {
29+
int val = super.pop();
30+
if (val == min()) {
31+
stack2.pop();
32+
}
33+
return val;
34+
}
35+
36+
public Integer min() {
37+
if (stack2.isEmpty()) {
38+
return Integer.MAX_VALUE;
39+
} else {
40+
return stack2.peek();
41+
}
42+
}
43+
44+
public static void main(String[] args) {
45+
MinStack min = new MinStack();
46+
min.push(3);
47+
min.push(4);
48+
min.push(2);
49+
System.out.println(min.min());
50+
}
51+
}

0 commit comments

Comments
 (0)