Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created June 30, 2014 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/384d682e551e1d2708b7 to your computer and use it in GitHub Desktop.
Save chrislukkk/384d682e551e1d2708b7 to your computer and use it in GitHub Desktop.
CareerCup_3.2 - Stack tracking min value
package Chapter3;
public class StackWithMinValue<T extends Comparable<T>> {
private Node<T> top = null;
public void push(T value) {
//minimum value under new top node
T min = top == null ? value : (top.min.compareTo(value) > 0 ? value
: top.min);
Node<T> next = top == null ? null : top;
Node<T> newTop = new Node<T>(value, next, min);
top = newTop;
}
public T pop() {
if (top == null)
return null;
Node<T> res = top;
top = top.next;
return res.value;
}
public T min() {
if (top == null)
return null;
return top.min;
}
public boolean isEmpty() {
return top == null;
}
public static void main(String[] args) {
StackWithMinValue<Integer> stack = new StackWithMinValue<>();
for(int i = 0; i < 10; i++) {
stack.push(10 - i);
}
while(!stack.isEmpty()) {
System.out.println("current min elem is " + stack.min());
System.out.println("top elem is " + stack.pop());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment