Created
June 20, 2014 05:50
-
-
Save chouclee/558ad32946d86acc14c6 to your computer and use it in GitHub Desktop.
[CC150][3.2] How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
import java.util.Random; | |
public class minStack<T extends Comparable<? super T>> { | |
Stack<T> data; | |
Stack<T> min; | |
T minimum; | |
int N; | |
public minStack() { | |
data = new Stack<T>(); | |
min = new Stack<T>(); | |
N = 0; | |
} | |
public void push(T item) { | |
data.add(item); | |
if (N == 0) | |
minimum = item; | |
else if (item.compareTo(minimum) < 0) | |
minimum = item; | |
min.add(minimum); | |
N++; | |
} | |
public T pop() { | |
if (N == 0) return null; | |
N--; | |
min.pop(); | |
return data.pop(); | |
} | |
public T min() { | |
if (N == 0) return null; | |
return min.peek(); | |
} | |
public String toString() { | |
return data.toString(); | |
} | |
public static void main(String[] args) { | |
minStack<Double> test = new minStack<Double>(); | |
Random rd = new Random(); | |
for (int i = 0; i < 5; i++) | |
test.push(rd.nextDouble()); | |
System.out.println(test.toString() + " min: " + test.min()); | |
test.pop(); | |
System.out.println(test.toString() + " min: " + test.min()); | |
test.pop(); | |
System.out.println(test.toString() + " min: " + test.min()); | |
test.pop(); | |
System.out.println(test.toString() + " min: " + test.min()); | |
test.pop(); | |
System.out.println(test.toString() + " min: " + test.min()); | |
test.pop(); | |
System.out.println(test.toString() + " min: " + test.min()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment