• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

My LinkedList Iterator - Can't print first element - No use of Java API

 
Dante Hawke
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I am currently trying to create my own Iterator for my own LinkedList class as part of a task, it's implementation must mirror that of the Java API LinkedList.

My BasicLinkedList works fine, however I have become a bit stuck working on its anonymous Iterator class, that should have a hasNext(), next() and remove() method.
At the moment it can hasNext() and print out the next() of all items in the list except for the first.

Here is my code.

BasicLinkedList:



Anonymous Iterator Class:




Inner Node Class:




Any help is appreciated, many thanks!

Cheers.
 
Lorand Komaromi
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dante Hawke wrote:private Node current = header;


You have to make sure that the first call to next() will return the first Node in the List. You could achieve this by setting current to a new Node instance whose next you would set to head...
 
Dante Hawke
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many thanks, that solved that problem, but now it doesn't print the last one in the LinkedList, I'm completely stumped here!


 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure about current.setNext(current.getNext())? Does that really remove the item?
 
Dante Hawke
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My hasNext() and next() method appear to work perfectly now under a few simple tests, my refined Iterator is as follows:

My current remove method is:


However, with some testing I have found that the remove method will always fail to remove the first Node.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks better, though I haven't gone through it carefully
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic