• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

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
Marshal
Posts: 71021
291
  • 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
Marshal
Posts: 71021
291
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks better, though I haven't gone through it carefully
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic