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.

Recommended Answers

All 3 Replies

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.

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?

please put some working code here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.