HackerRank Day 15 Solution in Python: Linked List

Today we will see the HackerRank Day 15 Solution in Python. The problem is named Linked List, part of 30 Days of code on HackerRank. Let’s get started!

Day 15: Linked List Problem statement

We have to complete the insert function in the given code so that it creates a new Node (pass data as the Node constructor argument) and inserts it at the tail of the linked list referenced by the head parameter. Once the new node is added, we have to return the reference to the head node.

Sample Input

4       
2       
3
4
1       

Sample Output

2 3 4 1

Explanation

The first input indicates the number of elements to be inserted. So the method will insert nodes into an initially empty list. The code returns a new node that contains the data value 2 as the head of the list. Then create and insert nodes 3, 4, and 1 at the tail of the list.

You can solve the problem here.

HackerRank Day 15 Solution in Python

class Node:
    #Constructor of Node class
    def __init__(self,data):
        self.data = data
        self.next = None 
        
class Solution: 
    #Method to print the list
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next
    
    #Function to insert new data into the linked list
    def insert(self, head, data):
        #If list is empty then return the list
        if head is None:
            return Node(data)
        
        #If list contains only head, return head
        elif not head.next:
            head.next = Node(data)
            return head
        
        #Temp node to iterate the list
        temp_node = head.next
        
        #Iterating the list till last element and insert new data at the end
        while temp_node.next:
            temp_node = temp_node.next
        temp_node.next = Node(data)
    
        return head

#object of Solution class
mylist= Solution()
#User input for number of elements to be inserted
T=int(input())
head=None
#User input for list elements
for i in range(T):
    data=int(input())
    head=mylist.insert(head,data)    
mylist.display(head); 	  

Code Explanation:

  • We have to create a function insert to add the elements to the list
  • If the head is null then return the list
  • If the next element to the head is null, then return the head
  • Otherwise, create a temporary node to iterate through the list
  • Initialize the temp variable with the first node, then iterate through the loop till the last element
  • Add the new data to the end of the list and return the head

Also Read:

Share:

Author: Ayush Purawr