Here\'s what I have:
public class Node{
Object data;
Node next;
Node(Object data, Node next){
this.data = data;
this.next = next
In your method to add a node, write a while loop that starts at the head and looks to see if the "next node" is null. If it is not, advance to the "next node" and repeat.
Once you are at the node that points to nothing, adding the node is as simple as reassigning the null reference to the node to be added.
Recursively navigate through each node until you hit the end.
public void navigate(Node insertNode)
{
if(next == null)
next = insertNode;
else
next.navigate(insertNode);
}
Node n = head;
while(n.getNext() != null){
n = n.getNext();
}
n.setNext(nodeToAdd);
That's not sorted, which I can't tell from your question if you want it sorted. Which opens up another whole can of worms such as what do you want to sort on, if you have a linked list of type Object there isn't really anything meaningful to sort on.
Start from the head:
Node currentNode = headNode;
while (node.getNext() != null) {
currentNode = currentNode.getNext();
}
currentNode.setNext(newNodeForInsertion);
A faster way is to store the last node of the list somewhere so you don't have to go through the whole list.
To add to the end, you'd have to walk to the end of the list (i.e., to where next=null) and add a new node there.
In the real world, you'd use an ArrayList for this and not bother with a linked list or manual structure at all.
A recursive solution:
public void addToEnd(Object data){
if (next==null)
next = new Node(data, null);
else
next.addToEnd(data);
}