I need to know how to solve the problem, here is my code (obviously incorrect) and I also attached the link of the hackerrank challenge. All of the previous answers is in older python and the exercise itself has considerably changed. All you have to do is insert data at the tail of the linked list. Thank you very much and have a good day.
def insertNodeAtTail(head, data):
if head == None:
head.data = data
return head
else:
while head:
head = head.next
head.data = data
return head
Found the answer
def insertNodeAtTail(head, data):
if head is None:
return SinglyLinkedListNode(data)
pnt = head
while pnt.next:
pnt = pnt.next
pnt.next = SinglyLinkedListNode(data)
return head
Well, right off the bat, I can see a big problem. You check for head == None
, and if that is True
, then you proceed to try to set the data
attribute in an object that doesn't exist...in None
. Also, you should be using if head is None
. If that succeeds, what you probably want to do is create a new Node object, set its data
attribute to the incoming data, and set head
to point to that new node.
You have a similar issue with the other half of your code. Your code doesn't add a Node in the case of an existing list either...it just changes the data that the last Node in the list is pointing to. Here, you want to create a Node containing your passed in data, and point node.next
to it.
I don't know the details of how you create a node, but here's about what your code should look like:
def insertNodeAtTail(head, data):
if head is None:
head = Node(data)
return head
else:
node = head
while node.next:
node = node.next
node.next = Node(data)
return head
It is assumed that Node()
sets its next
attribute to None
and sets its data
attribute to the passed in data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.