Change oldFirst.next = first
to first.next = oldFirst
in addFirst()
and it should work.
Right now first.next
after addFirst()
call isn't pointing to anything, as you're setting it to null
. This causes the hasNext()
method to return false, resulting in invalid iteration.