I wrote a method that will return the minimum element in a linked-list that operates in O(1) time. I tested and everything works fine. However, I was wondering if there is anything that I can do to make my code more efficient or cleaner.
public class Node {
//private Object item;
Node next;
Object item;
// constructor
public Node(Object item) {
this.item = item;
next = null;
}
}
public class MinElementInStack {
static Node stack;
static Node minStack;
public void push(int data) {
// push nodes into stack
Node last = new Node(data);
last.next = stack;
stack = last;
// check if node being pushed is new min
// if it is then push into minStack
if(minStack == null) { // for first node
Node toBePushed = new Node(data);
toBePushed.next = minStack;
minStack = toBePushed;
} else { // if int to be pushed is less than current min on stack
// then push it onto the stack, otherwise push the same min value from previous
int toBePushedInt = data;
if(toBePushedInt < (Integer)minStack.item) {
Node toBePushed = new Node(data);
toBePushed.next = minStack;
minStack = toBePushed;
} else {
Node toBePushed = new Node((Integer)minStack.item);
toBePushed.next = minStack;
minStack = toBePushed;
}
}
}
public void pop() {
if (stack != null && minStack != null) {
stack = stack.next;
minStack = minStack.next;
}
}
public int min() {
int min = (int) minStack.item;
return min;
}
public void print(Node node) {
Node temp = node;
while (temp != null) {
System.out.println(temp.item);
temp = temp.next;
}
}
public static void main(String[] args) {
MinElementInStack s = new MinElementInStack();
s.push(5);
s.push(-28);
s.push(8);
s.push(-50);
s.push(-4);
s.push(-38);
s.push(100);
System.out.println("Original Stack: ");
s.print(stack);
System.out.println();
System.out.println("Min Stack: ");
s.print(minStack);
System.out.println();
System.out.println("Minimum element in current stack: " + s.min());
}
}