Insert a node at a specific position in a linked list

  • + 0 comments

    Here's a solution in C#

    static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position)
        {
    		SinglyLinkedListNode node = new SinglyLinkedListNode(data);
            
            if(position == 0){
                node.next = llist;
                return node;
            }
            
            SinglyLinkedListNode cur = llist;
            
            for(int i = 0; i < position -  1; i++){
                if(cur != null){
                    cur = cur.next;    
                }
            }
            
            node.next = cur.next;
            cur.next = node;
            
    		return llist;
        }