Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Created July 2, 2014 15:56
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 bitcpf/1bb37f98c1c8ee17b0e2 to your computer and use it in GitHub Desktop.
Save bitcpf/1bb37f98c1c8ee17b0e2 to your computer and use it in GitHub Desktop.
package cc150_3_2;
public class MinStack<T extends Comparable<T>> {
private Node<T> top = null;
private Node<T> min_top = null;
public void push(T value){
T minvalue = top == null ? value :(min_top.item.compareTo(value) > 0 ? value : min_top.item);
Node<T> temp = top == null ? new Node<T>(value): top;
Node<T> min_temp = min_top == null ? new Node<T>(value):min_top;
Node<T> next = new Node<T>(value);
Node<T> min_next = new Node<T>(minvalue);
next.next = temp;
min_next = min_temp;
top = next;
min_top = min_temp;
}
public T pop(){
if (top == null)
return null;
Node<T> current = top;
top = top.next;
min_top = min_top;
return current.item;
}
public T min(){
if (top == null)
return null;
Node<T> current = min_top;
return current.item;
}
public boolean isEmpty() {
return top == null;
}
public static void main(String[] args){
MinStack test = new MinStack();
for (int i = 5;i < 15; i++){
test.push(i);
}
while(!test.isEmpty()) {
System.out.println("Current min is " + test.min());
System.out.println("Current top element is " + test.pop());
}
}
}
public class Node<Item> {
Item item = null;
Node next = null;
public Node(Item item){
this.item = item;
this.next = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment