I'm currently studying Linked List and on Iterators(using Lafore's).
I am not sure as to why we need Iterators in the first place.
Say your class Link looks like below.
class Link{
public int iData; // data
public double dData; /d/ data
public Link next; //reference to next link
//----------------------------------
public Link(int id, double dd){
iData = id; //initialize data
dData = dd;// 'next' is automatically set to null.
}
//----------------------------------
public void displayLink(){
System.out.print("{"+iData+", "+dData+"} ");
}
//----------------------------------
}//end class Link
And your LinkList class has a field Link first and some operations for the list.
My question is
Why can't I just add an int variable(ex: int count;) as a field for the Link class and then just increment it whenever it's called instead of building a whole class ,called Iterators, just to traverse back and forth in the list?
The book says
One problem with this approach is that you might need more than one such reference, just as you often use several array indices at the same time.
What does it mean? Can you give me an example of when this problem occurs?
Thank you in advance.
public Link next_by_idata;andpublic Link next_by_ddata;. It would be a little more complicated to manage, but would allow accessing either way very rapidly.