Insert a node at a specific position in a linked list

Sort by

recency

|

1535 Discussions

|

  • + 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;
        }
    
  • + 0 comments

    The starting boiler plate in Java needs to be refactored or else it will never compile.

  • + 0 comments

    Updated python solution

    def insertNodeAtPosition(llist, data, position):
        if llist is None:
            return SinglyLinkedListNode(data, None)
            
        current = llist
        for i in range(position):
            prev = current
            current = current.next
            
        Node = SinglyLinkedListNode(data)
        prev.next = Node
        Node.next = current
        
        return llist
    
  • + 0 comments

    Inserting a node at a specific position in a linked list involves traversing the list to the desired position, adjusting the pointers of the previous and next nodes to include the new node. This operation ensures the list maintains its integrity by properly linking the new node at the correct location without breaking the chain. Betbhai 9

  • + 0 comments

    My C solution. ` SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) { SinglyLinkedListNode *newNode = malloc(sizeof(SinglyLinkedListNode *));

    newNode->data = data;
    
    if (llist == NULL) {
        return newNode;
    }
    SinglyLinkedListNode *current = llist;
    SinglyLinkedListNode *temp = malloc(sizeof(SinglyLinkedListNode *));
    
    //temp->data = data;
    for (int i = 0; i < position - 1; i++) {
        current = current->next;
    }
    temp = current->next;
    current->next = newNode;
    newNode->next = temp;
    
    return llist;
    

    } `