I am trying to implement a stack with Java:
public class Stack<E> {
Node top = null;
public void push(E data) {
Node node = new Node(data);
if (null != top) {
node.next = top;
}
top = node;
}
public E pop() {
if (null == top) {
throw new IllegalStateException("Stack is empty");
} else {
E data = top.data;
top = top.next;
return data;
}
}
public E peek() {
if (null == top) {
throw new IllegalStateException("Stack is empty");
} else {
E data = top.data;
return data;
}
}
public void print() {
if (null == top) {
throw new IllegalStateException("Stack is empty");
} else {
Node node = top;
while(null != node) {
System.out.println(node.data);
node = node.next;
}
}
}
private class Node {
Node next;
E data;
Node(E data) {
this.data = data;
}
}
}
I am looking for feedback for the implementation. Also, I wanted to know if the pop() implementation can cause a memory leak?