Insert a Node at the Tail of a Linked List

  • + 1 comment

    CORRECTION to above code For Java 8

    public static Node insert(Node head,int data) { //Complete this method if (head == null){ head = new Node(data); head.data = data; } else { Node node = head; while (node.next != null){ node = node.next; } node.next = new Node(data); node.next.data = data; } return head;
    }

    Make sure to pass by value the int data when creating a new instance of Node. The constructor in class Node (line 7 of code) demands that you specify an int when creating a new Node object. Remember a class constructor is the blueprint for stating what parameters (requirements) an object needs before it can be created. Coded for us already is the method signature of our insert function, which tells us that we already have an int data availabe for us to use. It's being passed by value into the funtion. So make sure that this is the value used when creating new Node objects.

    Thank you to Elnaz for your contribution. I was stuck on this one for a while and could not have solved this without you.