Insert a Node at the Tail of a Linked List

  • + 2 comments

    Why must you declare a "Node node = head"? Initially I had:

    if(head == null)
        {
            head = new Node();
            head.data = data;
        }
        else{
            while(head.next != null) head = head.next;
            head.next = new Node();
            head.next.data = data;
        }
        return head;
    

    But this method doesn't work. May you explain why? Thank you!