We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,642 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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.

3
Contributors
3
Replies
8 Hours
Discussion Span
6 Months Ago
Last Updated
5
Views
Question
Answered
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

please put some working code here.

jalpesh_007
Posting Whiz
328 posts since Sep 2010
Reputation Points: 4
Solved Threads: 36
Skill Endorsements: 3
Question Answered as of 6 Months Ago by jalpesh_007 and Taywin

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0780 seconds using 2.71MB