Insert a node at a specific position in a linked list

Sort by

recency

|

51 Discussions

|

  • + 0 comments

    Here is hackerrank insert a node at a specific position in a linked list solution in python java c++ c and javascript

  • + 0 comments

    C++14

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) 
    {
        SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);
        
        SinglyLinkedListNode* aux;
        aux = llist;
        
        
        if (position == 0)
        {
            newNode->next = llist;
            llist->next = newNode;    
        }   
        else
        {
            for (int i = 0; i < position - 1; i++) 
            {
                aux = aux->next;
            }
            newNode->next = aux->next;
            aux->next = newNode;
        }
        
        return llist;
    }
    
  • + 0 comments
    def insertNodeAtPosition(llist, data, position):
        # Write your code here
        data = SinglyLinkedListNode(data)
        if position == 0:
            data.next = llist
            return data
        
        current = llist
        for _ in range(position - 1):
            current = current.next
        
        data.next = current.next
        current.next = data
        
        return llist
        
    
  • + 0 comments
    def insertNodeAtPosition(llist, data, position):
        # Create the new node with the given data
        inserted_node = SinglyLinkedListNode(data)
        # If inserting at the head (position 0)
        if position == 0:
            inserted_node.next = llist
            return inserted_node
        # Traverse the list to find the insertion point
        curr = llist
        curr_pos = 1
        # Loop until the position before the insertion point
        while curr_pos != position:
            curr = curr.next
            curr_pos += 1
        # Insert the new node at the given position
        inserted_node.next = curr.next
        curr.next = inserted_node
        return llist
    
  • + 0 comments
    function insertNodeAtPosition($llist, $data, $position) {
        if($position == 0) {
            $node = new SinglyLinkedListNode($data);
            $node->next = $llist;
            return $node;
        }
        $llist->next = insertNodeAtPosition($llist->next, $data, $position - 1);
        return $llist;
    }