class MinStack {
Node stack;
int size;
public void push(int data) {
if (size == Integer.MAX_VALUE)
throw new StackOverflowError();
Node node = new Node(data);
int min = Integer.MAX_VALUE;
if (stack != null && stack.min != null)
min = stack.min.data;
if (data <= min)
node.min = node;
else
node.min = stack.min;
node.next = stack;
stack = node;
size++;
}
public void pop() {
if (stack == null)
throw new EmptyStackException();
stack = stack.next;
size--;
}
public int top() {
if (stack == null)
throw new EmptyStackException();
return stack.data;
}
public int getMin() {
if (stack == null)
throw new EmptyStackException();
if (stack.min == null)
return 0;
return stack.min.data;
}
class Node {
int data;
Node next;
Node min;
public Node(int data) {
this.data = data;
}
}
}
Comments