Insert a node at a specific position in a linked list

Sort by

recency

|

52 Discussions

|

  • + 0 comments

    def insertNodeAtPosition(llist, data, position):

    dummy = SinglyLinkedListNode(data)
    curr = llist
    i=0
    while curr is not None:
        i = i+1
        next_node = curr.next # save next node 
        if i == position:
            curr.next = dummy  #set current nodes next pointer to dummy
            dummy.next = next_node #set dummy's next pointer to next_node
        curr = next_node    #move to the next_node
    return llist
    
  • + 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