Insert a Node at the Tail of a Linked List

  • + 0 comments

    Here a java solution using recursion.

      static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) {
            //create the new node
            if(head == null){
                SinglyLinkedListNode node = new SinglyLinkedListNode(data);
                return node;
            }
            //if the head.next is null, I will insert the new node there
            if(head.next == null)
                head.next = insertNodeAtTail(head.next, data);
            //move to the next    
            else    
                insertNodeAtTail(head.next, data);
            return head;
        }