Java - add a node to the end of a list?

前端 未结 8 648
有刺的猬
有刺的猬 2021-01-16 03:55

Here\'s what I have:

public class Node{
    Object data;
    Node next;

    Node(Object data, Node next){
        this.data = data;
        this.next = next         


        
相关标签:
8条回答
  • 2021-01-16 04:20

    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.

    0 讨论(0)
  • 2021-01-16 04:22

    Recursively navigate through each node until you hit the end.

    public void navigate(Node insertNode)
    {
        if(next == null)
            next = insertNode;
        else
            next.navigate(insertNode);
    }
    
    0 讨论(0)
  • 2021-01-16 04:26
    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.

    0 讨论(0)
  • 2021-01-16 04:31

    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.

    0 讨论(0)
  • 2021-01-16 04:32

    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.

    0 讨论(0)
  • 2021-01-16 04:39

    A recursive solution:

    public void addToEnd(Object data){
        if (next==null) 
          next = new Node(data, null);
        else
          next.addToEnd(data);
    }
    
    0 讨论(0)
提交回复
热议问题