Here's my implementation of a Stack in Java, all feedback welcome.
import java.util.Iterator;
public class Stack<T> implements Iterable<T> {
private Node head = null;
private int size;
@Override
public Iterator<T> iterator() {
return new StackIterator();
}
private class Node<T>{
public Node(T data){
this.data = data;
this.next = null;
}
T data;
Node next;
}
private class StackIterator implements Iterator<T>{
private Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T item = (T) current.data;
current = current.next;
return item;
}
}
public Stack(){
size = 0;
head = null;
}
public boolean isEmpty(){
return head == null;
}
public void push(T item){
Node p = new Node(item);
if(head == null){
head = p;
size++;
return;
}
p.next = head;
head = p;
size++;
}
public T pop(){
Node current = head;
if(current.next == null){
head = null;
}else{
try {
head = head.next;
size--;
}catch (Exception e){
System.out.println("Popping off an empty stack:" + e);
}
}
return (T)current.data;
}
public void trace(){
Node current = head;
while(current != null){
System.out.println(current.data);
current = current.next;
}
}
}