Singly Linked List method
I am trying to input an int into the end of a singly linked list. I have already created the code to put a number at the end of the list but when I go to print it out, it only prints out (in my test class) the int that will go at the end of the list rather than printing out the whole list(and then .
mylist.addEnd(8);
System.out.println("after addEnd");
anIterator = mylist.iterator(); // reads mylist collection
for (int i=0;i<mylist.getSize();i++)
System.out.print(anIterator.next() + " ");
If this seems correct then something must be wrong with my addEnd method.
FUTURECompEng
Junior Poster in Training
50 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
If you already use an iterator, you should the iterator's method. The way you do (using for-loop from the list size) is unsafe and may cause problem. Use while(anIterator.hasNext()) is much safer.
Now, are you sure that your addEnd() method is implemented correctly? If the result is unexpected, you may need to show how you implement the addEnd() of your class.
Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17
Okay so I think there is something wrong with my method, but I made progress now I am getting null in place of the end element. So what I think I need to do is
endList.next=new node(); //at the end of the list a new node will be added
How would I go about adding this new node before endList?
FUTURECompEng
Junior Poster in Training
50 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 6 Months Ago by
jalpesh_007
and
Taywin