HackerRank Day 24 Solution in Python: More Linked Lists

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

Day 24: More Linked Lists Problem statement

We are given a Node class and a Node object that has an integer data field, and a Node instance pointer, pointing to another node (i.e.: the next node in a list). A removeDuplicates function is declared which takes a pointer to the node of a linked list as a parameter. We have to Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list.

Sample Input

6
1
2
2
3
3
4

Sample Output

1 2 3 4 

Explanation: First input is the number of elements followed by the elements to be inserted in list. The values 2 and 3 both occur twice in the list, so we remove the two duplicate nodes. We then return our updated (ascending) list

You can solve the problem here.

HackerRank Day 24 Solution in Python

class Node:
    def __init__(self,data):
        self.data = data
        self.next = None 
        
class Solution: 
    #Function to insert the new node with data
    def insert(self,head,data):
            p = Node(data)           
            if head==None:
                head=p
            elif head.next==None:
                head.next=p
            else:
                start=head
                while(start.next!=None):
                    start=start.next
                start.next=p
            return head  
    
    #Function to display the list
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next

    #Function to remove duplicates
    def removeDuplicates(self,head):
        if not head:
            return head
        new_node = head
        #Iterate through the list
        while new_node.next:
            #If the current node and next node data are same
            if new_node.data == new_node.next.data:
                new_node.next = new_node.next.next
            else:
                new_node = new_node.next
        #Return head of the updated list 
        return head

mylist= Solution()
T=int(input())
head=None
for i in range(T):
    data=int(input())
    head=mylist.insert(head,data)    
head=mylist.removeDuplicates(head)
mylist.display(head); 

Code Explanation

  • Create a function to remove duplicates in the list
  • If the head is null, return the head. Else store the head in a variable
  • Iterate through the list, and check if the current node and next node data are the same
  • If it is the same delete the current element, else move to the next element
  • After reaching the end of the list, return the head value of this updated list without duplicates

Also Read:

Share:

Author: Keerthana Buvaneshwaran