Insert a node at a specific position in a linked list

Sort by

recency

|

1543 Discussions

|

  • + 0 comments

    def insertNodeAtPosition(llist, data, position): # Write your code here if llist is None: llist = SinglyLinkedList() llist.data = data else: current = llist for i in range(1, position): current = current.next

        new_next = SinglyLinkedList()
        new_next.data = data
        new_next.next = current.next
        current.next = new_next
    return llist
    
  • + 0 comments

    Haskell boilerplate contains a mistake which makes this problem unsolvable in Haskell

  • + 0 comments

    "This operation requires traversing the linked list up to the node just before the desired position. It’s important to handle edge cases, such as inserting at the head (position 0) or beyond the current length of the list. Proper pointer management is critical to ensure no nodes are lost and the list remains intact." Gold365.site

  • + 0 comments

    def insertNodeAtPosition(head, data, position): # Write your code here newnode=SinglyLinkedListNode(data) current=head if head is not None: count=1 while current.next: if count==position: newnode.next=current.next current.next=newnode count+=1 current=current.next return head

  • + 0 comments

    My Java solution with linear time complexity and constant space complexity:

    public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) {
        SinglyLinkedListNode newNode = new SinglyLinkedListNode(data);
        
        // Insertion at head
        if (position == 0) {
            newNode.next = llist;
            return newNode;
        }
        
        SinglyLinkedListNode curr = llist;
        
        // Traverse to the node before the insertion point
        for (int i = 0; i < position - 1; i++) {
            if (curr != null) {
                curr = curr.next;
            }
        }
    
        // Insert the new node
        newNode.next = curr.next;
        curr.next = newNode;
    
        return llist;
    }