Insert a node at a specific position in a linked list

Sort by

recency

|

1552 Discussions

|

  • + 0 comments

    For Python3 Platform

    def insertNodeAtPosition(llist, data, position):
        new_node = SinglyLinkedListNode(data)
        
        if(position == 0):
            new_node.next = llist
            llist = new_node
        else:
            temp = llist
            for _ in range(position-1):
                temp = temp.next
            
            new_node.next = temp.next
            temp.next = new_node
        
        return llist
    
  • + 0 comments

    there is a compilation error in java please fix it

  • + 0 comments

    Here is Insert a node at a specific position in a linked list in python, java, c++ and c programming - https://programmingoneonone.com/hackerrank-insert-a-node-at-a-specific-position-in-a-linked-list-solution.html

  • + 0 comments
    def insertNodeAtPosition(llist, data, position):
        # Write your code here
        if position == 0:
            head = SinglyLinkedListNode(data)
            head.next = llist
            return head
        cur = llist
        for i in range(position-1):
            cur = cur.next
        temp = cur.next
        cur.next = SinglyLinkedListNode(data)
        cur.next.next = temp 
        return llist
    
  • + 0 comments
    def insertNodeAtPosition(llist, data, position):
        new_node = SinglyLinkedListNode(data)
    
        if position == 0:
            new_node.next = llist
            return new_node
    
        current = llist
        index = 0
    
        while index < position - 1:
            current = current.next
            index += 1
    
    
        new_node.next = current.next
        current.next = new_node
    
        return llist