Insert a Node at the Tail of a Linked List

  • + 0 comments

    My Java solution with o(n) time complexity and o(1) space complexity:

    static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) {
            if(head == null) return new SinglyLinkedListNode(data);
            
            SinglyLinkedListNode curr = head;
            while(curr.next != null) curr = curr.next;
            curr.next = new SinglyLinkedListNode(data);
            return head;
        }