O 03 zz linked list insertion at beginning hackerrank
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() Show Inserting a node at the beginning of a linked listThe new node will be added at the beginning of a linked list. ExampleAssume 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 Insert a node at a specific position in a linked list
Given a singly linked list, a position and an element, the task is to write a program to insert that element in a linked list at a given position. Examples: Input: 3->5->8->10, data = 2, position = 2 Output: 3->2->5->8->10 Input: 3->5->8->10, data = 11, position = 5 Output: 3->5->8->10->11Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach: To insert a given data at a specified position, the below algorithm is to be followed:
Below is the implementation of the above algorithm. C++
Java
Python3
C#
Javascript
Time Complexity: O(N) Article Tags : Data Structures Linked List cpp-double-pointer Practice Tags : Data Structures Linked List Read Full Article |