관리 메뉴

솜씨좋은장씨

[HackerRank] Insert a node at a specific position in a linked list (Python) 본문

Programming/코딩 1일 1문제

[HackerRank] Insert a node at a specific position in a linked list (Python)

솜씨좋은장씨 2021. 2. 8. 12:56
728x90
반응형

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node.

A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty.

Example
head refers to the first node in the list 1 -> 2 -> 3
data = 4

position = 2

Insert a node at position 2 with data = 4. The new list is 1 -> 2 -> 4 -> 3

Function Description Complete the function insertNodeAtPosition in the editor below. It must return a reference to the head node of your finished list.

insertNodeAtPosition has the following parameters:

  • head: a SinglyLinkedListNode pointer to the head of the list
  • data: an integer value to insert as data in your new node
  • position: an integer position to insert the new node, zero based indexing

Returns

  • SinglyLinkedListNode pointer: a reference to the head of the revised list

Input Format

The first line contains an integer n, the number of elements in the linked list.
Each of the next n lines contains an integer SinglyLinkedListNode[i].data.
The next line contains an integer data, the data of the node that is to be inserted.
The last line contains an integer position.

Constraints

  • 1 <= n <= 1000
  • 1<= SinglyLinkedListNode[i ].data <= 1000, where SinglyLinkedListNode[ i ] is the ith element of the linked list.
  • 0 <= position <= n.

Sample Input

3 16 13 7 1 2

Sample Output

16 13 1 7

Explanation

The initial linked list is 16 -> 13 -> 7. Insert 1 at the position  which currently has 7 in it. The updated linked list is

16 -> 13 -> 1 -> 7.

 

Solution

#!/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):
    answer = SinglyLinkedListNode(0)
    
    result = answer
    
    idx = 0
    
    while True:
        if head == None:
            break
    
        if idx != position:
            val = head.data
            head = head.next
        else:
            val = data
        
        idx = idx + 1
            
        answer.next = SinglyLinkedListNode(val)
        answer = answer.next
        
    return result.next
    

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()

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments