I am trying to implement Stack using a linked list. Looking for code-review, best practices and optimizations.
public class StackUsingLinkedList<T> {
private Node<T> top;
int size;
public StackUsingLinkedList() {
}
private static class Node<T> {
Node<T> next;
T item;
public Node (T item, Node<T> next) {
this.item = item;
this.next = next;
}
}
/**
* Push the item into the stack
*
* @param item the item to be pushed.
*/
public void push(T item) {
final Node<T> node = new Node<T>(item, top);
top = node;
size++;
}
/**
* Pops the item from the stack
*
* @return the popped item
* @throws EmptyStackException if attempt is made to access/pop out of an empty stack.
*/
public T pop() {
if (top == null) {
throw new EmptyStackException();
}
T item = top.item;
top = top.next;
return item;
}
/**
* Returns the item at top of the stack.
*
* @return the item at top of stack.
* @throws EmptyStackException if attempt is made to access empty stack
*/
public T peek () {
if (top == null) {
throw new EmptyStackException();
}
return top.item;
}
public int size() {
return size;
}
public boolean isEmpty() {
return top == null;
}
public static void main(String[] args) {
StackUsingLinkedList<Integer> s = new StackUsingLinkedList<Integer>();
s.push(10);
s.push(20);
// expected 20, 10.
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}