Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a Node at the Tail of a Linked List python HackerRank

Its a very simple program of adding a node at the end of a link list. I dont know what mistake I am doing. has it something to do with the exoected output of hackerRank or there's a mistake in my code. I m trying to implement the Python2

class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node
def Insert(head, data):

    if (head.head == None):
        head.head = Node(data)
    else:
        current = head.head
        while (current.next != None) and (current.data == data):
                           current = current.next
        current.next = Node(data)

Heres a link to the question. https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list

like image 605
Ojas Kale Avatar asked May 15 '26 01:05

Ojas Kale


2 Answers

If you have to add at the end of linklist then It's not needed to test current.data == data, Below code should be enough-

def Insert(head, data):

    if (head == None):
        head = Node(data)
    else:
        current = head
        while (current.next != None):
            current = current.next
        current.next = Node(data)
    return head

Also note that Python you don't need to use () after if and while.

like image 89
AlokThakur Avatar answered May 17 '26 14:05

AlokThakur


Your code has several problems:

  • head is either None or an instance of Node. Neither has a head attribute, so head.head makes no sense.
  • None is a singleton, so test something is None instead of something == None and something is not None instead of something != None.
  • You're supposed to return the head of the modified list. Your function doesn't return anything.
like image 41
das-g Avatar answered May 17 '26 14:05

das-g