Zz linked list-insertion at beginning hackerrank solution

Problem solution in Python programming.

#!/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 # # class Node[object]: def __init__[self, data=None, next_node=None]: self.data = data self.next = next_node def insertNodeAtPosition[head, data, position]: if position==0: head = Node[data,head] return head else: temp_head = head while position>1: temp_head = temp_head.next position = position -1 temp_head.next = Node[data,temp_head.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[]




Inserting a node at the beginning of a linked list

The new node will be added at the beginning of a linked list.


Example

Assume that the linked list has elements: 20 30 40 NULL

If we insert 100, it will be added at the beginning of a linked list.

After insertion, the new linked list will be

100 20 30 40 NULL



Video liên quan

Bài mới nhất

Chủ Đề