Insert a node at a specific position in a linked list

Sort by

recency

|

1530 Discussions

|

  • + 0 comments

    Here is my C++ solution, you can watch the explanation here : https://youtu.be/jCPAp_UIzAs

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) {
        SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);
        if(position == 0) {
            newNode->next = llist;
            return newNode;
        }
        SinglyLinkedListNode* curr = llist;
        while(position - 1) {
            position--;
            curr = curr -> next;
        }
        newNode -> next = curr->next;
        curr->next = newNode;
        return llist;
    }
    
  • + 0 comments

    simplest python solution:

    def insertNodeAtPosition(llist, data, position):
        new_node = SinglyLinkedListNode(data)
        curr = llist
        prev = llist
            
        for i in range(position):
            prev = curr
            curr = curr.next
            
        prev.next = new_node
        new_node.next = curr
        
        return llist
    
  • + 0 comments

    Is the problem statement wrong? The head pointer can't be null because n >= 1. Am I right?

  • + 0 comments

    For C# csharp you cannot compile as given.

    class Result
    {
        public static SinglyLinkedListNode insertNodeAtPosition(...)
        {
    		...
        }
    }
    

    You need to modify the above code by removing class Result{} block and remove the public modifer on the method.

    You should be left with...

        static SinglyLinkedListNode insertNodeAtPosition(...)
        {
    		...
        }
    

    This should allow your code to compile.

  • + 0 comments

    Hackerrank fix your code in provided Solution for c#, throws error