Insert a node at a specific position in a linked list

Sort by

recency

|

34 Discussions

|

  • + 0 comments
    def insertNodeAtPosition(llist, data, position):
        # Write your code here
        counter = 0
        root = SinglyLinkedList()
       
        next_node = llist
        while ( next_node is not None):
    
            if (counter == position):
                root.insert_node(data)
            else:
                temp = next_node
                root.insert_node(temp.data)
                next_node = temp.next
            counter += 1
        return root.head
    
  • + 0 comments

    Python 3

    However I look at this, the 'position 0' case seems special as you return a different 'head'. The simplest option I could see was to treat it as a separate case.

    I quite like the proposed naming and structure here of 'next_index' being the count, starting from 1, and running through the llist until you find the right point to do the insert... although maybe 'node_count' or something would be more technically correct than 'index'

    def insertNodeAtPosition(llist, data, position):
        
        new_node = SinglyLinkedListNode(data)
        
        if position == 0:
            new_node.next = llist
            return new_head
        
        this = llist
        next_index = 1
        while next_index != position:
            this = this.next
            next_index += 1
        
        new_node.next = this.next
        this.next = new_node
        return llist
    
  • + 0 comments

    c++

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) { SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);

    if (position == 0) {
        newNode->next = llist;
        return newNode;
    }
    
    SinglyLinkedListNode* temp = llist;
    while (--position > 0 && temp->next) {
        temp = temp->next;
    }
    
    SinglyLinkedListNode* tempNext = temp->next;
    temp->next = newNode;
    newNode->next = tempNext;
    
    return llist;
    

    }

  • + 0 comments
        def insert(self,data,position):
            new_node = Node(data)
            current = self.head
    
            if position == 0:
                new_node.next = self.head
                self.head = new_node
            else:
                while position>1:
                    current = current.next
                    position-=1
                next = current.next
                current.next = new_node
                current.next.next = next
    
                new_node = next
    
  • + 0 comments

    in java 8 getting error in main methode and declearing staitc how to resolve that