Problem:https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem

Sample Code:


def insertNodeAtPosition(head, data, position):
    new=SinglyLinkedListNode(data)
    if position==0:
        new.next=head
        head=new
        return head
    ptr=head
    c=1
    while ptr.next is not None:
        if c== position:
            new.next=ptr.next
            ptr.next=new
            break
        c+=1
        ptr=ptr.next
    return head          
#!/bin/python3

import math
import os
import random
import re
import sys

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 insert_node(self, node_data):
        node = SinglyLinkedListNode(node_data)

        if not self.head:
            self.head = node
        else:
            self.tail.next = node


        self.tail = node

def print_singly_linked_list(node, sep, fptr):
    while node:
        fptr.write(str(node.data))

        node = node.next

        if node:
            fptr.write(sep)

# Complete the insertNodeAtPosition function below.

#
# For your reference:
#
# SinglyLinkedListNode:
#     int data
#     SinglyLinkedListNode next
#
#
def insertNodeAtPosition(head, data, position):
    new=SinglyLinkedListNode(data)
    if position==0:
        new.next=head
        head=new
        return head
    ptr=head
    c=1
    while ptr.next is not None:
        if c== position:
            new.next=ptr.next
            ptr.next=new
            break
        c+=1
        ptr=ptr.next
    return head            

         
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    llist_count = int(input())

    llist = SinglyLinkedList()

    for _ in range(llist_count):
        llist_item = int(input())
        llist.insert_node(llist_item)

    data = int(input())

    position = int(input())

    llist_head = insertNodeAtPosition(llist.head, data, position)

    print_singly_linked_list(llist_head, ' ', fptr)
    fptr.write('\n')

    fptr.close()

Explanation:

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top