Insert a node at a specific position in a linked list

  • + 0 comments
        public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) {
            SinglyLinkedListNode newNode = new SinglyLinkedListNode(data);
    
            // If inserting at the head (position 0)
            if (position == 0) {
                newNode.next = llist;
                return newNode;
            }
            
            // Traverse the list to find the node before the desired position
            SinglyLinkedListNode current = llist;
            for (int i = 0; i < position - 1 && current != null; i++) {
                current = current.next;
            }
            
            // Insert the new node
            if (current != null) {
                newNode.next = current.next;
                current.next = newNode;
            }
            
            return llist;
        }