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
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With