Created
June 30, 2014 03:23
-
-
Save chrislukkk/384d682e551e1d2708b7 to your computer and use it in GitHub Desktop.
CareerCup_3.2 - Stack tracking min value
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
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