Insert a Node at the front of the linked list hackerrank solution

JavaScript: Inserting a Node at the Head of a Linked List

Explained Solution to a HackerRank Problem

Insert a Node at the front of the linked list hackerrank solution

For today’s algorithm, we will insert a node at the head of a singly linked list. Here is the challenge that I picked from HackerRank:

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and…

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 print_singly_linked_list(node, sep, fptr): while node: fptr.write(str(node.data)) node = node.next if node: fptr.write(sep) def insertNodeAtHead(llist, data): # Write your code here node = SinglyLinkedListNode(data) if llist: node.next = llist return node 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_head = insertNodeAtHead(llist.head, llist_item) llist.head = llist_head print_singly_linked_list(llist.head, '\n', fptr) fptr.write('\n') fptr.close()