0

This question is a hackerrank challenge. link here: https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list

"""
Insert Node at a specific position in a linked list
head input could be None as well for empty list
Node is defined as

 class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

 return back the head of the linked list in the below method. 
"""
#This is a "method-only" submission.
#You only need to complete this method.
def InsertNth(head, data, position):
    node = head 
    if position == 0: 
        node = Node(data)
        node.data = data 
        node.next = head 
        return node
    else: 
        while position > 0: 
            node = node.next 

            i = node.next
            node.next = Node(data)
            node.next.next = i 
            return head

my current output is 321024, but I need it to be 310542. Any help is greatly appreciated!

1
  • Your while loop doesn't make any sense; it's going to always run exactly one time. Commented Jan 14, 2017 at 3:17

10 Answers 10

4
def InsertNth(head, data, position):
    start = head
    if position == 0:
        return Node(data, head)
    while position > 1:
        head = head.next
        position -= 1
    head.next = Node(data, head.next)
    return start

I didn't test it, but something like this should be right. You first want to save a copy of the reference to the start of the list. Then, you should check if this is being added to the front of the list, in which case you should return a new starting node with the proper value. Otherwise, you cycle through the list until you get to the position you want at which point you set the next node to have the proper value and remaining list.

Sign up to request clarification or add additional context in comments.

1 Comment

I would give you a plus 1 if I could. this explanation helps, thank you @Vedranh13. It does work btw.
4
def insertNodeAtPosition(head, data, position):
    prev_node = head
    if position == 0:
        new_node = SinglyLinkedListNode(data)
        new_node.next = head
        return new_node

    while prev_node is not None:
        new_node = SinglyLinkedListNode(data)

        for _ in range(position-1):
            prev_node = prev_node.next

        new_node.next = prev_node.next
        prev_node.next = new_node
        return head

Comments

1

We have 2 possible options.

  1. If the data should be add in the first (position = 0) and then we should change the head pointer to the current node or
  2. The position should be added in the k-th place and we update the list using the head.next and position-1 recursively

def insertNodeAtPosition(self, head, data, position):
    if (position == 0) | (head==None):
        return SinglyLinkedListNode(data, head)
    else:
        head.next = self.insertNodeAtPosition(head.next, data, position-1)
        return head

1 Comment

Ad a brief explanation
0
 def InsertNth(head, data, position):
        node = head
        i = 0
        temp = Node(data)
        while node is not None:
            if i == at:
                temp.nextnode = node.nextnode
                node.nextnode = temp
                break
            i += 1
            node = node.nextnode

Comments

0
class SinglyLinkedListNode:
    def __init__(self, node_data):
        self.data = node_data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

def insertNodeAtPosition(head, data, position):
    pos = 0
    current_head = head
    previous_head = head
    while pos <= position:
        if pos == position:
            new_head = SinglyLinkedListNode(data)
            previous_head.next = new_head
            new_head.next = current_head
            return head
        else:
            pos += 1
            previous_head = current_head
            current_head = current_head.next
    return head

Comments

0
def insertNodeAtPosition(head, data, position):
    currNode = head
    while position > 1:
        position -= 1
        currNode = currNode.next

    temp = currNode
    node = SinglyLinkedListNode(data)
    node.next = temp.next
    currNode.next = node
    return head

Comments

0
def insertNodeAtPosition(head, data, position):
    positer = 0
    temp = head
    while temp:
        if positer == position-1:
            newNode = SinglyLinkedListNode(data)
            newNode.next = temp.next
            temp.next = newNode
            break
        else:
            positer+=1
            temp = temp.next
    return head

1 Comment

Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
0
def insert_after(self, data, pos):
    new_node = Node(data)
    prev = self.head
    pos = pos - 1
    if pos == 0:
        self.insert_front(data)
        return
    while pos > 1:
        prev = prev.next
        pos -= 1
    new_node.next = prev.next
    prev.next = new_node

Comments

0

Here is a recursive solution in opposition to the naive implementation

def insertNodeAtPosition(node, data, position):
    if not node:
        return None
        
    if position <= 1:
        new_node = SinglyLinkedListNode(data)
        new_node.next = node.next
        node.next = new_node
        return node
    
    node.next = insertNodeAtPosition(node.next, data, position - 1)
    
    return node

Comments

-1
def insert(self, data, position):
    counter = 1
    current = self.head
    if position > 1:
        while current and counter < position:
            if counter == position - 1:
                data.next = current.next
                current.next = data
                current = current.next
                counter += 1
    elif position == 1:
        data.next = self.head
        self.head = new_element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.